From fd82728899a46b373ae4ce4c0c63c4bc7231d975 Mon Sep 17 00:00:00 2001 From: Grzegorz Date: Sun, 29 Nov 2026 13:46:07 +0100 Subject: [PATCH 1/2] feat(addons): add fulfillment executor foundation --- .env.example | 8 + .../ProcessAddonExecutionsCommand.php | 47 ++ app/Contracts/ServiceAddonModuleInterface.php | 42 ++ app/Enums/AddonExecutionAction.php | 9 + app/Enums/AddonExecutionStatus.php | 32 ++ app/Enums/AddonOperation.php | 22 + app/Jobs/ExecuteServiceAddonJob.php | 36 ++ app/Models/ProductAddon.php | 28 +- app/Models/ServiceAddon.php | 26 +- app/Models/ServiceAddonExecution.php | 60 +++ app/Models/ServiceAddonExecutionAttempt.php | 33 ++ app/Providers/ModuleServiceProvider.php | 7 + app/Services/Addons/AddonExecutionService.php | 462 ++++++++++++++++++ app/Support/Addons/AddonInstruction.php | 39 ++ config/addons.php | 19 + ...0001_add_fulfillment_to_product_addons.php | 36 ++ ...0002_add_fulfillment_to_service_addons.php | 33 ++ ..._create_service_addon_executions_table.php | 45 ++ ...service_addon_execution_attempts_table.php | 32 ++ docs/developer/addon-executor.md | 201 ++++++++ lang/de/addons.php | 22 + lang/en/addons.php | 22 + lang/pl/addons.php | 22 + lang/tr/addons.php | 22 + lang/zh/addons.php | 22 + mkdocs.yml | 1 + modules/Servers/AddonTest/AddonTestModule.php | 250 ++++++++++ routes/console.php | 3 + tests/Feature/AddonExecutorTest.php | 329 +++++++++++++ tests/Feature/ModuleCompletenessTest.php | 4 + 30 files changed, 1912 insertions(+), 2 deletions(-) create mode 100644 app/Console/Commands/ProcessAddonExecutionsCommand.php create mode 100644 app/Contracts/ServiceAddonModuleInterface.php create mode 100644 app/Enums/AddonExecutionAction.php create mode 100644 app/Enums/AddonExecutionStatus.php create mode 100644 app/Enums/AddonOperation.php create mode 100644 app/Jobs/ExecuteServiceAddonJob.php create mode 100644 app/Models/ServiceAddonExecution.php create mode 100644 app/Models/ServiceAddonExecutionAttempt.php create mode 100644 app/Services/Addons/AddonExecutionService.php create mode 100644 app/Support/Addons/AddonInstruction.php create mode 100644 config/addons.php create mode 100644 database/migrations/2026_11_30_000001_add_fulfillment_to_product_addons.php create mode 100644 database/migrations/2026_11_30_000002_add_fulfillment_to_service_addons.php create mode 100644 database/migrations/2026_11_30_000003_create_service_addon_executions_table.php create mode 100644 database/migrations/2026_11_30_000004_create_service_addon_execution_attempts_table.php create mode 100644 docs/developer/addon-executor.md create mode 100644 lang/de/addons.php create mode 100644 lang/en/addons.php create mode 100644 lang/pl/addons.php create mode 100644 lang/tr/addons.php create mode 100644 lang/zh/addons.php create mode 100644 modules/Servers/AddonTest/AddonTestModule.php create mode 100644 tests/Feature/AddonExecutorTest.php diff --git a/.env.example b/.env.example index 7b2a46e96..a508f442e 100644 --- a/.env.example +++ b/.env.example @@ -36,6 +36,14 @@ DB_PASSWORD= # Optional: use Unix socket instead of TCP (leave commented for TCP) # DB_SOCKET=/var/run/mysqld/mysqld.sock +# ── Add-on fulfilment ─────────────────────────────────────────────────────── +# Off by default. This only controls the technical add-on executor; sales, +# invoicing and billing are unaffected. +ADDONS_FULFILLMENT_ENABLED=false +# The AddonTest module is only registered in local/testing, and only when +# this is on. Never enable it in production. +ADDONS_TEST_MODULE_ENABLED=false + # ── Session / Cache / Queue ───────────────────────────────────────────────── # "file" drivers work out of the box. Switch to redis/database once tables exist. SESSION_DRIVER=file diff --git a/app/Console/Commands/ProcessAddonExecutionsCommand.php b/app/Console/Commands/ProcessAddonExecutionsCommand.php new file mode 100644 index 000000000..91ca07b6a --- /dev/null +++ b/app/Console/Commands/ProcessAddonExecutionsCommand.php @@ -0,0 +1,47 @@ +enabled()) { + $this->info('Addon fulfillment is disabled.'); + + return self::SUCCESS; + } + + $query = ServiceAddonExecution::query() + ->whereIn('status', [ + AddonExecutionStatus::Pending->value, + AddonExecutionStatus::Retry->value, + ]) + ->where(function ($query): void { + $query->whereNull('available_at')->orWhere('available_at', '<=', now()); + }); + + if ($id = $this->option('id')) { + $query->whereKey((int) $id); + } + + $executions = $query->orderBy('id')->limit(max(1, (int) $this->option('limit')))->get(); + + foreach ($executions as $execution) { + $executor->execute($execution); + } + + $this->info('Processed '.$executions->count().' add-on execution(s).'); + + return self::SUCCESS; + } +} diff --git a/app/Contracts/ServiceAddonModuleInterface.php b/app/Contracts/ServiceAddonModuleInterface.php new file mode 100644 index 000000000..ccb33ef59 --- /dev/null +++ b/app/Contracts/ServiceAddonModuleInterface.php @@ -0,0 +1,42 @@ +, + * parameters?: array + * } + */ + public function addonCapabilities(): array; + + /** + * @return array{success: bool, message: string, data?: array} + */ + public function validateAddon(Service $service, AddonInstruction $instruction): array; + + /** + * @return array{success: bool, message: string, data?: array} + */ + public function applyAddon(Service $service, AddonInstruction $instruction): array; + + /** + * @return array{success: bool, message: string, data?: array} + */ + public function removeAddon(Service $service, AddonInstruction $instruction): array; + + /** + * @return array{success: bool, message: string, data?: array} + */ + public function getAddonStatus(Service $service, AddonInstruction $instruction): array; +} diff --git a/app/Enums/AddonExecutionAction.php b/app/Enums/AddonExecutionAction.php new file mode 100644 index 000000000..a68e9fdd4 --- /dev/null +++ b/app/Enums/AddonExecutionAction.php @@ -0,0 +1,9 @@ + */ + public array $backoff = [60, 300]; + + public int $timeout = 300; + + public function __construct(public int $executionId) {} + + public function handle(AddonExecutionService $executor): void + { + $execution = ServiceAddonExecution::find($this->executionId); + + if (! $execution) { + return; + } + + $executor->execute($execution); + } +} diff --git a/app/Models/ProductAddon.php b/app/Models/ProductAddon.php index 1554d5264..c365d775d 100644 --- a/app/Models/ProductAddon.php +++ b/app/Models/ProductAddon.php @@ -21,7 +21,10 @@ class ProductAddon extends Model protected $table = 'product_addons'; - protected $fillable = ['name', 'description', 'packages', 'hidden', 'retired', 'sort_order', 'tax']; + protected $fillable = [ + 'name', 'description', 'packages', 'hidden', 'retired', 'sort_order', 'tax', + 'fulfillment_module', 'operation', 'parameter', 'value', 'unit', 'options', 'auto_fulfill', + ]; protected function casts(): array { @@ -29,6 +32,29 @@ protected function casts(): array 'hidden' => 'boolean', 'retired' => 'boolean', 'tax' => 'boolean', + 'options' => 'array', + 'auto_fulfill' => 'boolean', + ]; + } + + /** Whether this addon carries anything the executor can perform. */ + public function hasFulfillmentConfig(): bool + { + return trim((string) $this->operation) !== '' + && trim((string) $this->parameter) !== ''; + } + + /** The snapshot copied to a ServiceAddon at purchase time. */ + public function fulfillmentConfig(): array + { + return [ + 'module' => $this->fulfillment_module, + 'operation' => $this->operation, + 'parameter' => $this->parameter, + 'value' => $this->value, + 'unit' => $this->unit, + 'options' => $this->options ?? [], + 'auto_fulfill' => (bool) $this->auto_fulfill, ]; } diff --git a/app/Models/ServiceAddon.php b/app/Models/ServiceAddon.php index ef29c1c8f..47da566d7 100644 --- a/app/Models/ServiceAddon.php +++ b/app/Models/ServiceAddon.php @@ -2,14 +2,17 @@ namespace App\Models; +use App\Enums\AddonExecutionStatus; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Eloquent\Relations\HasOne; class ServiceAddon extends Model { use HasFactory; - protected $fillable = ['order_id', 'service_id', 'addon_id', 'client_id', 'server_id', 'qty', 'amount', 'prorated', 'proration_days', 'proration_cycle_days', 'billing_cycle', 'next_due_date', 'first_invoice_date', 'status', 'notes']; + protected $fillable = ['order_id', 'service_id', 'addon_id', 'client_id', 'server_id', 'qty', 'amount', 'prorated', 'proration_days', 'proration_cycle_days', 'billing_cycle', 'next_due_date', 'first_invoice_date', 'status', 'notes', 'fulfillment_config', 'fulfillment_status', 'fulfilled_at', 'fulfillment_error']; protected function casts(): array { @@ -20,6 +23,9 @@ protected function casts(): array 'prorated' => 'boolean', 'proration_days' => 'integer', 'proration_cycle_days' => 'integer', + 'fulfillment_config' => 'array', + 'fulfillment_status' => AddonExecutionStatus::class, + 'fulfilled_at' => 'datetime', ]; } @@ -43,6 +49,24 @@ public function addon() return $this->belongsTo(ProductAddon::class, 'addon_id'); } + public function executions(): HasMany + { + return $this->hasMany(ServiceAddonExecution::class); + } + + public function latestExecution(): HasOne + { + return $this->hasOne(ServiceAddonExecution::class)->latestOfMany(); + } + + public function latestCompletedApply(): HasOne + { + return $this->hasOne(ServiceAddonExecution::class) + ->where('action', 'apply') + ->where('status', 'completed') + ->latestOfMany(); + } + /** What to call this on an invoice or in the customer's service page. */ public function label(): string { diff --git a/app/Models/ServiceAddonExecution.php b/app/Models/ServiceAddonExecution.php new file mode 100644 index 000000000..5dd554020 --- /dev/null +++ b/app/Models/ServiceAddonExecution.php @@ -0,0 +1,60 @@ + AddonExecutionAction::class, + 'status' => AddonExecutionStatus::class, + 'request_payload' => 'array', + 'response_payload' => 'array', + 'attempts' => 'integer', + 'max_attempts' => 'integer', + 'available_at' => 'datetime', + 'started_at' => 'datetime', + 'finished_at' => 'datetime', + ]; + } + + public function serviceAddon(): BelongsTo + { + return $this->belongsTo(ServiceAddon::class); + } + + public function service(): BelongsTo + { + return $this->belongsTo(Service::class); + } + + public function client(): BelongsTo + { + return $this->belongsTo(Client::class); + } + + public function sourceInvoice(): BelongsTo + { + return $this->belongsTo(Invoice::class, 'source_invoice_id'); + } + + public function attempts(): HasMany + { + return $this->hasMany(ServiceAddonExecutionAttempt::class, 'execution_id')->orderBy('attempt_no'); + } +} diff --git a/app/Models/ServiceAddonExecutionAttempt.php b/app/Models/ServiceAddonExecutionAttempt.php new file mode 100644 index 000000000..0d7c25e92 --- /dev/null +++ b/app/Models/ServiceAddonExecutionAttempt.php @@ -0,0 +1,33 @@ + AddonExecutionStatus::class, + 'request_payload' => 'array', + 'response_payload' => 'array', + 'attempt_no' => 'integer', + 'started_at' => 'datetime', + 'finished_at' => 'datetime', + ]; + } + + public function execution(): BelongsTo + { + return $this->belongsTo(ServiceAddonExecution::class, 'execution_id'); + } +} diff --git a/app/Providers/ModuleServiceProvider.php b/app/Providers/ModuleServiceProvider.php index 50a86f158..3cb9f7569 100644 --- a/app/Providers/ModuleServiceProvider.php +++ b/app/Providers/ModuleServiceProvider.php @@ -23,6 +23,7 @@ use Modules\Registrars\OVH\OvhRegistrar; use Modules\Registrars\ResellerClub\ResellerClubRegistrar; use Modules\Servers\AaPanel\AaPanelModule; +use Modules\Servers\AddonTest\AddonTestModule; use Modules\Servers\CPanel\CPanelModule; use Modules\Servers\Custom\CustomModule; use Modules\Servers\DirectAdmin\DirectAdminModule; @@ -68,6 +69,12 @@ public function register(): void // Built-in server modules $registry->registerServer('custom', CustomModule::class); + // Addon Executor test module — never registered in production. + if (app()->environment(['local', 'testing']) + && config('addons.fulfillment.test_module_enabled', false)) { + $registry->registerServer('addon_test', AddonTestModule::class); + } + // Built-in gateway modules $registry->registerGateway('banktransfer', BankTransferModule::class); $registry->registerGateway('stripe', StripeModule::class); diff --git a/app/Services/Addons/AddonExecutionService.php b/app/Services/Addons/AddonExecutionService.php new file mode 100644 index 000000000..8dd07af01 --- /dev/null +++ b/app/Services/Addons/AddonExecutionService.php @@ -0,0 +1,462 @@ +enabled()) { + return null; + } + + $config = $this->configuration($addon); + if ($config === null) { + return null; + } + + return $this->enqueue($addon, AddonExecutionAction::Apply, $config, $reason, $invoice); + } + + public function enqueueRemoval(ServiceAddon $addon, string $reason = 'cancelled'): ?ServiceAddonExecution + { + if (! $this->enabled()) { + return null; + } + + $applied = ServiceAddonExecution::query() + ->where('service_addon_id', $addon->id) + ->where('action', AddonExecutionAction::Apply->value) + ->where('status', AddonExecutionStatus::Completed->value) + ->latest('id') + ->first(); + + if (! $applied) { + return null; + } + + $config = data_get($applied->request_payload, 'configuration'); + if (! is_array($config)) { + $config = $this->configuration($addon); + } + + if ($config === null || ! is_array($config)) { + return null; + } + + return $this->enqueue( + $addon, + AddonExecutionAction::Remove, + $config, + $reason, + null, + $applied->id + ); + } + + public function execute(ServiceAddonExecution $execution): bool + { + if (! $this->enabled()) { + return false; + } + + $claimed = ServiceAddonExecution::query() + ->whereKey($execution->id) + ->whereIn('status', [AddonExecutionStatus::Pending->value, AddonExecutionStatus::Retry->value]) + ->update([ + 'status' => AddonExecutionStatus::Processing->value, + 'started_at' => now(), + 'finished_at' => null, + 'attempts' => DB::raw('attempts + 1'), + ]); + + if ($claimed === 0) { + return false; + } + + $execution->refresh(); + $attempt = ServiceAddonExecutionAttempt::create([ + 'execution_id' => $execution->id, + 'attempt_no' => $execution->attempts, + 'status' => AddonExecutionStatus::Processing->value, + 'request_payload' => $execution->request_payload, + 'started_at' => now(), + ]); + + try { + $addon = $execution->serviceAddon; + $service = $execution->service; + + if (! $addon || ! $service) { + return $this->finish($execution, AddonExecutionStatus::Failed, null, __('addons.executor.service_or_addon_missing'), null, $attempt); + } + + $problem = $this->validateExecution($execution, $addon, $service); + if ($problem !== null) { + return $this->finish($execution, $problem['status'], null, $problem['message'], null, $attempt); + } + + $module = $this->provisioning->resolveModule($service); + + if (! $module instanceof ServiceAddonModuleInterface) { + return $this->finish( + $execution, + AddonExecutionStatus::Unsupported, + null, + __('addons.executor.module_not_supported'), + null, + $attempt + ); + } + + $config = data_get($execution->request_payload, 'configuration'); + if (! is_array($config)) { + $config = $this->configuration($addon); + } + + if ($config === null || ! is_array($config)) { + return $this->finish($execution, AddonExecutionStatus::Failed, null, __('addons.executor.configuration_missing'), null, $attempt); + } + + $problem = $this->validateCapabilities($module, $config); + if ($problem !== null) { + return $this->finish($execution, $problem['status'], null, $problem['message'], null, $attempt); + } + + $instruction = $this->instruction($execution, $addon, $config); + $validation = $module->validateAddon($service, $instruction); + + if (! ($validation['success'] ?? false)) { + return $this->finish( + $execution, + AddonExecutionStatus::Failed, + $validation, + (string) ($validation['message'] ?? __('addons.executor.validation_failed')), + null, + $attempt + ); + } + + $result = $execution->action === AddonExecutionAction::Remove + ? $module->removeAddon($service, $instruction) + : $module->applyAddon($service, $instruction); + + if (! ($result['success'] ?? false)) { + $manual = (bool) data_get($result, 'data.manual_required', false); + $retryable = (bool) data_get($result, 'data.retryable', true); + + if ($manual) { + return $this->finish( + $execution, + AddonExecutionStatus::ManualRequired, + $result, + (string) ($result['message'] ?? __('addons.executor.manual_required')), + null, + $attempt + ); + } + + $status = $retryable && $execution->attempts < $execution->max_attempts + ? AddonExecutionStatus::Retry + : AddonExecutionStatus::Failed; + + return $this->finish( + $execution, + $status, + $result, + (string) ($result['message'] ?? __('addons.executor.operation_failed')), + $status === AddonExecutionStatus::Retry ? now()->addMinutes(5 * (2 ** max(0, $execution->attempts - 1))) : null, + $attempt + ); + } + + return $this->finish($execution, AddonExecutionStatus::Completed, $result, (string) ($result['message'] ?? ''), null, $attempt); + } catch (Throwable $e) { + Log::error('AddonExecutionService::execute failed', [ + 'execution_id' => $execution->id, + 'service_addon_id' => $execution->service_addon_id, + 'error' => $e->getMessage(), + ]); + + $status = $execution->attempts < $execution->max_attempts + ? AddonExecutionStatus::Retry + : AddonExecutionStatus::Failed; + $availableAt = $status === AddonExecutionStatus::Retry + ? now()->addMinutes(5 * (2 ** max(0, $execution->attempts - 1))) + : null; + + return $this->finish($execution, $status, null, $e->getMessage(), $availableAt, $attempt); + } + } + + public function retry(ServiceAddonExecution $execution): bool + { + if (! $this->enabled() || in_array($execution->status, [ + AddonExecutionStatus::Completed, + AddonExecutionStatus::Processing, + AddonExecutionStatus::Cancelled, + ], true)) { + return false; + } + + $execution->forceFill([ + 'status' => AddonExecutionStatus::Retry, + 'available_at' => now(), + 'finished_at' => null, + 'result_message' => null, + ])->save(); + + return $this->execute($execution->fresh()); + } + + private function enqueue( + ServiceAddon $addon, + AddonExecutionAction $action, + array $config, + string $reason, + ?Invoice $invoice = null, + ?int $appliedExecutionId = null + ): ServiceAddonExecution { + $hash = $this->configurationHash($config); + $key = $action === AddonExecutionAction::Remove + ? 'remove:'.$addon->id.':'.($appliedExecutionId ?? 'unknown') + : 'apply:'.$addon->id.':'.$hash; + + $execution = ServiceAddonExecution::firstOrCreate( + ['idempotency_key' => $key], + [ + 'service_addon_id' => $addon->id, + 'service_id' => $addon->service_id, + 'client_id' => $addon->client_id, + 'source_invoice_id' => $invoice?->id, + 'action' => $action, + 'status' => AddonExecutionStatus::Pending, + 'module' => $config['module'] ?? null, + 'operation' => $config['operation'] ?? null, + 'parameter' => $config['parameter'] ?? null, + 'value' => isset($config['value']) ? (string) $config['value'] : null, + 'unit' => $config['unit'] ?? null, + 'request_payload' => [ + 'reason' => $reason, + 'configuration' => $config, + 'configuration_hash' => $hash, + 'applied_execution_id' => $appliedExecutionId, + ], + 'max_attempts' => self::MAX_ATTEMPTS, + ] + ); + + if (in_array($execution->status, [AddonExecutionStatus::Pending, AddonExecutionStatus::Retry], true)) { + DB::afterCommit(fn () => ExecuteServiceAddonJob::dispatch($execution->id)); + } + + return $execution; + } + + /** + * @return array|null + */ + private function configuration(ServiceAddon $addon): ?array + { + $config = $addon->fulfillment_config; + + if (! is_array($config)) { + return null; + } + + if (trim((string) ($config['operation'] ?? '')) === '' + || trim((string) ($config['parameter'] ?? '')) === '') { + return null; + } + + return $config; + } + + /** + * @return array{status: AddonExecutionStatus, message: string}|null + */ + private function validateExecution(ServiceAddonExecution $execution, ServiceAddon $addon, Service $service): ?array + { + if ((int) $addon->service_id !== (int) $service->id) { + return ['status' => AddonExecutionStatus::Failed, 'message' => __('addons.executor.invalid_service')]; + } + + if ((int) $addon->client_id !== (int) $service->client_id + || (int) $execution->client_id !== (int) $addon->client_id) { + return ['status' => AddonExecutionStatus::Failed, 'message' => __('addons.executor.invalid_owner')]; + } + + if ($execution->action === AddonExecutionAction::Apply) { + if (strtolower((string) $service->status) !== 'active' || ! $addon->isActive()) { + return ['status' => AddonExecutionStatus::Failed, 'message' => __('addons.executor.not_active')]; + } + } elseif (in_array(strtolower((string) $service->status), ['terminated', 'fraud'], true)) { + return ['status' => AddonExecutionStatus::Cancelled, 'message' => __('addons.executor.service_ended')]; + } + + return null; + } + + /** + * @return array{status: AddonExecutionStatus, message: string}|null + */ + private function validateCapabilities(ServiceAddonModuleInterface $module, array $config): ?array + { + $operation = AddonOperation::tryFrom((string) ($config['operation'] ?? '')); + if (! $operation) { + return ['status' => AddonExecutionStatus::Unsupported, 'message' => __('addons.executor.unsupported_operation')]; + } + + $capabilities = $module->addonCapabilities(); + $operations = $capabilities['operations'] ?? []; + + if (! in_array($operation->value, $operations, true)) { + return ['status' => AddonExecutionStatus::Unsupported, 'message' => __('addons.executor.unsupported_operation')]; + } + + $parameter = (string) ($config['parameter'] ?? ''); + $parameters = $capabilities['parameters'] ?? []; + + if (! array_key_exists($parameter, $parameters)) { + return ['status' => AddonExecutionStatus::Unsupported, 'message' => __('addons.executor.unsupported_parameter')]; + } + + $definition = $parameters[$parameter]; + $expectedUnit = $definition['unit'] ?? null; + + if ($expectedUnit !== null && $expectedUnit !== '' && $expectedUnit !== ($config['unit'] ?? null)) { + return ['status' => AddonExecutionStatus::Failed, 'message' => __('addons.executor.invalid_unit')]; + } + + if ($operation->usesNumericValue()) { + if (! is_numeric($config['value'] ?? null)) { + return ['status' => AddonExecutionStatus::Failed, 'message' => __('addons.executor.invalid_value')]; + } + + $value = (float) $config['value']; + + if (isset($definition['min']) && $value < (float) $definition['min']) { + return ['status' => AddonExecutionStatus::Failed, 'message' => __('addons.executor.value_below_minimum')]; + } + + if (isset($definition['max']) && $value > (float) $definition['max']) { + return ['status' => AddonExecutionStatus::Failed, 'message' => __('addons.executor.value_above_maximum')]; + } + } + + return null; + } + + private function instruction(ServiceAddonExecution $execution, ServiceAddon $addon, array $config): AddonInstruction + { + return new AddonInstruction( + executionId: $execution->id, + serviceAddonId: $addon->id, + operation: (string) $execution->operation, + parameter: (string) $execution->parameter, + value: $config['value'] ?? null, + unit: $execution->unit, + options: is_array($config['options'] ?? null) ? $config['options'] : [], + configurationHash: (string) data_get($execution->request_payload, 'configuration_hash', ''), + appliedExecutionId: data_get($execution->request_payload, 'applied_execution_id'), + ); + } + + private function finish( + ServiceAddonExecution $execution, + AddonExecutionStatus $status, + ?array $result, + string $message, + ?\DateTimeInterface $availableAt = null, + ?ServiceAddonExecutionAttempt $attempt = null + ): bool { + $terminal = $status->isFinished(); + $error = $status === AddonExecutionStatus::Completed ? null : $message; + + DB::transaction(function () use ($execution, $status, $result, $message, $availableAt, $attempt, $terminal, $error): void { + $execution->forceFill([ + 'status' => $status, + 'response_payload' => $result['data'] ?? [], + 'result_message' => $message, + 'available_at' => $availableAt, + 'finished_at' => $terminal ? now() : null, + ])->save(); + + if ($attempt) { + $attempt->forceFill([ + 'status' => $status, + 'response_payload' => $result['data'] ?? [], + 'error' => $error, + 'finished_at' => now(), + ])->save(); + } + + if ($execution->serviceAddon) { + $execution->serviceAddon->forceFill([ + 'fulfillment_status' => $status === AddonExecutionStatus::Completed && $execution->action === AddonExecutionAction::Remove + ? AddonExecutionStatus::Cancelled + : $status, + 'fulfilled_at' => $status === AddonExecutionStatus::Completed ? now() : $execution->serviceAddon->fulfilled_at, + 'fulfillment_error' => $error, + ])->save(); + } + }); + + return $status === AddonExecutionStatus::Completed; + } + + /** + * @param array $config + */ + private function configurationHash(array $config): string + { + $normalized = [ + 'module' => $config['module'] ?? null, + 'operation' => $config['operation'] ?? null, + 'parameter' => $config['parameter'] ?? null, + 'value' => $config['value'] ?? null, + 'unit' => $config['unit'] ?? null, + 'options' => $config['options'] ?? [], + ]; + + $this->sortRecursive($normalized); + + return hash('sha256', json_encode($normalized, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) ?: ''); + } + + private function sortRecursive(array &$value): void + { + ksort($value); + + foreach ($value as &$child) { + if (is_array($child)) { + $this->sortRecursive($child); + } + } + } +} diff --git a/app/Support/Addons/AddonInstruction.php b/app/Support/Addons/AddonInstruction.php new file mode 100644 index 000000000..a82137f86 --- /dev/null +++ b/app/Support/Addons/AddonInstruction.php @@ -0,0 +1,39 @@ + $options + */ + public function __construct( + public int $executionId, + public int $serviceAddonId, + public string $operation, + public string $parameter, + public mixed $value, + public ?string $unit, + public array $options, + public string $configurationHash, + public ?int $appliedExecutionId = null, + ) {} + + /** + * @return array + */ + public function toArray(): array + { + return [ + 'execution_id' => $this->executionId, + 'service_addon_id' => $this->serviceAddonId, + 'operation' => $this->operation, + 'parameter' => $this->parameter, + 'value' => $this->value, + 'unit' => $this->unit, + 'options' => $this->options, + 'configuration_hash' => $this->configurationHash, + 'applied_execution_id' => $this->appliedExecutionId, + ]; + } +} diff --git a/config/addons.php b/config/addons.php new file mode 100644 index 000000000..0b725cebb --- /dev/null +++ b/config/addons.php @@ -0,0 +1,19 @@ + [ + 'enabled' => env('ADDONS_FULFILLMENT_ENABLED', false), + + /* + * The AddonTest service module is only registered in local/testing + * environments, and only when this switch is on. It has no manifest + * and must never be discoverable in production. + */ + 'test_module_enabled' => env('ADDONS_TEST_MODULE_ENABLED', false), + ], +]; diff --git a/database/migrations/2026_11_30_000001_add_fulfillment_to_product_addons.php b/database/migrations/2026_11_30_000001_add_fulfillment_to_product_addons.php new file mode 100644 index 000000000..f41a24667 --- /dev/null +++ b/database/migrations/2026_11_30_000001_add_fulfillment_to_product_addons.php @@ -0,0 +1,36 @@ +string('fulfillment_module')->nullable()->after('packages'); + $table->string('operation', 30)->nullable()->after('fulfillment_module'); + $table->string('parameter')->nullable()->after('operation'); + $table->string('value')->nullable()->after('parameter'); + $table->string('unit')->nullable()->after('value'); + $table->json('options')->nullable()->after('unit'); + $table->boolean('auto_fulfill')->default(false)->after('options'); + }); + } + + public function down(): void + { + Schema::table('product_addons', function (Blueprint $table) { + $table->dropColumn([ + 'fulfillment_module', + 'operation', + 'parameter', + 'value', + 'unit', + 'options', + 'auto_fulfill', + ]); + }); + } +}; diff --git a/database/migrations/2026_11_30_000002_add_fulfillment_to_service_addons.php b/database/migrations/2026_11_30_000002_add_fulfillment_to_service_addons.php new file mode 100644 index 000000000..5c5e57a63 --- /dev/null +++ b/database/migrations/2026_11_30_000002_add_fulfillment_to_service_addons.php @@ -0,0 +1,33 @@ +json('fulfillment_config')->nullable()->after('notes'); + $table->string('fulfillment_status', 30)->default('not_configured')->after('status'); + $table->timestamp('fulfilled_at')->nullable()->after('fulfillment_status'); + $table->text('fulfillment_error')->nullable()->after('fulfilled_at'); + + $table->index('fulfillment_status'); + }); + } + + public function down(): void + { + Schema::table('service_addons', function (Blueprint $table) { + $table->dropIndex(['fulfillment_status']); + $table->dropColumn([ + 'fulfillment_config', + 'fulfillment_status', + 'fulfilled_at', + 'fulfillment_error', + ]); + }); + } +}; diff --git a/database/migrations/2026_11_30_000003_create_service_addon_executions_table.php b/database/migrations/2026_11_30_000003_create_service_addon_executions_table.php new file mode 100644 index 000000000..007da7b0e --- /dev/null +++ b/database/migrations/2026_11_30_000003_create_service_addon_executions_table.php @@ -0,0 +1,45 @@ +id(); + $table->foreignId('service_addon_id')->nullable()->constrained('service_addons')->nullOnDelete(); + $table->foreignId('service_id')->nullable()->constrained('services')->nullOnDelete(); + $table->foreignId('client_id')->nullable()->constrained('clients')->nullOnDelete(); + $table->foreignId('source_invoice_id')->nullable()->constrained('invoices')->nullOnDelete(); + $table->string('action', 20); + $table->string('status', 30)->default('pending'); + $table->string('module')->nullable(); + $table->string('operation', 30)->nullable(); + $table->string('parameter')->nullable(); + $table->string('value')->nullable(); + $table->string('unit')->nullable(); + $table->json('request_payload')->nullable(); + $table->json('response_payload')->nullable(); + $table->text('result_message')->nullable(); + $table->string('idempotency_key', 191)->unique(); + $table->unsignedInteger('attempts')->default(0); + $table->unsignedInteger('max_attempts')->default(5); + $table->timestamp('available_at')->nullable(); + $table->timestamp('started_at')->nullable(); + $table->timestamp('finished_at')->nullable(); + $table->timestamps(); + + $table->index(['status', 'available_at']); + $table->index(['service_addon_id', 'action']); + $table->index(['service_id', 'created_at']); + }); + } + + public function down(): void + { + Schema::dropIfExists('service_addon_executions'); + } +}; diff --git a/database/migrations/2026_11_30_000004_create_service_addon_execution_attempts_table.php b/database/migrations/2026_11_30_000004_create_service_addon_execution_attempts_table.php new file mode 100644 index 000000000..93dab3a18 --- /dev/null +++ b/database/migrations/2026_11_30_000004_create_service_addon_execution_attempts_table.php @@ -0,0 +1,32 @@ +id(); + $table->foreignId('execution_id')->constrained('service_addon_executions')->cascadeOnDelete(); + $table->unsignedInteger('attempt_no'); + $table->string('status', 30); + $table->json('request_payload')->nullable(); + $table->json('response_payload')->nullable(); + $table->text('error')->nullable(); + $table->timestamp('started_at')->nullable(); + $table->timestamp('finished_at')->nullable(); + $table->timestamps(); + + $table->unique(['execution_id', 'attempt_no']); + $table->index(['status', 'created_at']); + }); + } + + public function down(): void + { + Schema::dropIfExists('service_addon_execution_attempts'); + } +}; diff --git a/docs/developer/addon-executor.md b/docs/developer/addon-executor.md new file mode 100644 index 000000000..1c45da681 --- /dev/null +++ b/docs/developer/addon-executor.md @@ -0,0 +1,201 @@ +# Add-on executor + +The add-on executor is the technical fulfilment layer for **product add-ons** +(`ProductAddon` / `ServiceAddon`). It is separate from `AddonManager` and +`modules/Addons`, which manage panel extensions such as BankPayments or KSeF. + +## Stage 1 scope + +Stage 1 provides the foundation only: + +- database fields and history tables, +- `ServiceAddonModuleInterface`, +- `AddonInstruction`, +- `AddonExecutionService`, +- `ExecuteServiceAddonJob`, +- `pnlcs:addon-executions:process`, +- the guarded `AddonTest` module, +- tests and this document. + +Payment listeners, `activateOrderAddons()` integration, cancellation wiring, +admin screens and real server modules are deliberately not part of Stage 1. + +## Feature flags + +`config/addons.php`: + +```php +'fulfillment' => [ + 'enabled' => env('ADDONS_FULFILLMENT_ENABLED', false), + 'test_module_enabled' => env('ADDONS_TEST_MODULE_ENABLED', false), +], +``` + +Both default to **off**. The executor checks `enabled` before creating or +executing anything. Disabling it does not change product add-on sales, +invoices, renewals or billing statuses. + +The test module requires both `APP_ENV` to be `local` or `testing` and +`ADDONS_TEST_MODULE_ENABLED=true`. It has no `pnlcs.json`, is not registered +in production, and every add-on method checks the guard again. + +## Data model + +### `product_addons` + +`fulfillment_module`, `operation`, `parameter`, `value`, `unit`, `options` +(JSON), `auto_fulfill` (default `false`). + +`ProductAddon::fulfillmentConfig()` returns the snapshot shape copied to a +purchased add-on. + +### `service_addons` + +`fulfillment_config` (JSON snapshot), `fulfillment_status` (default +`not_configured`), `fulfilled_at`, `fulfillment_error`. + +The existing `status` remains the billing status. It is never used as proof +that the technical operation succeeded. + +### `service_addon_executions` + +One row per idempotent instruction. Important fields: + +- `action`: `apply` / `remove`, +- `status`: `pending`, `processing`, `completed`, `failed`, `retry`, + `cancelled`, `manual_required`, `unsupported`, +- `idempotency_key` (unique), +- snapshot fields (`module`, `operation`, `parameter`, `value`, `unit`), +- `request_payload`, `response_payload`, `result_message`, +- `attempts`, `max_attempts`, `available_at`, timestamps. + +### `service_addon_execution_attempts` + +One row per attempt, with `attempt_no`, status, request, response, error and +start/finish timestamps. Earlier attempts are never overwritten. + +## Module contract + +Implement `App\Contracts\ServiceAddonModuleInterface` in addition to the +module's existing `ServerModuleInterface`. `ServerModuleInterface` itself is +unchanged, so modules without add-on support remain compatible. + +```php +use App\Contracts\ServiceAddonModuleInterface; +use App\Models\Service; +use App\Support\Addons\AddonInstruction; + +class MyModule implements ServerModuleInterface, ServiceAddonModuleInterface +{ + public function addonCapabilities(): array + { + return [ + 'operations' => ['increment', 'set'], + 'parameters' => [ + 'storage_quota' => ['unit' => 'GB', 'min' => 0], + ], + ]; + } + + public function validateAddon(Service $service, AddonInstruction $instruction): array + { + return ['success' => true, 'message' => 'OK', 'data' => []]; + } + + public function applyAddon(Service $service, AddonInstruction $instruction): array + { + // Use $instruction->executionId for external idempotency keys. + return ['success' => true, 'message' => 'Applied', 'data' => []]; + } + + public function removeAddon(Service $service, AddonInstruction $instruction): array + { + return ['success' => true, 'message' => 'Removed', 'data' => []]; + } + + public function getAddonStatus(Service $service, AddonInstruction $instruction): array + { + return ['success' => true, 'message' => 'OK', 'data' => []]; + } +} +``` + +`AddonInstruction` contains the execution id, service add-on id, operation, +parameter, value, unit, options and configuration hash. A remove instruction +also carries `appliedExecutionId`. + +The executor validates the operation and parameter against +`addonCapabilities()` before calling the module. + +## Idempotency + +Keys: + +```text +apply:{service_addon_id}:{sha256(canonical snapshot)} +remove:{service_addon_id}:{applied_execution_id} +``` + +`idempotency_key` is unique. Retry reuses the same execution. A completed +execution cannot be executed again. + +Execution claims are atomic: + +```text +pending/retry -> processing +``` + +Only one worker can claim a row. Module calls are not wrapped in a database +transaction; only the claim and result writes are transactional. + +## Queue + +`ExecuteServiceAddonJob` runs after the execution is committed. The scheduler +also runs: + +```bash +php artisan pnlcs:addon-executions:process +``` + +every five minutes. It processes due `pending` and `retry` executions. The +command accepts `--id` for a single execution and `--limit` for a batch. +`MAX_ATTEMPTS` and exponential backoff are stored on the execution row. + +## Test module + +`modules/Servers/AddonTest/AddonTestModule.php` is intentionally not +discoverable by manifest. It simulates effects in +`service.module_data['addon_test']` and supports: + +- `simulate=fail_once` — transient failure, then success, +- `simulate=fail_permanent` — permanent failure, +- `simulate=refuse_remove` — safe removal refusal, +- normal `increment`, `set`, `decrement`, `attach`, `detach`. + +It never calls a remote server. It is safe only for local/testing and is +guarded by both the environment and `ADDONS_TEST_MODULE_ENABLED`. + +## Example executor use + +```php +$executor = app(\App\Services\Addons\AddonExecutionService::class); + +$execution = $executor->enqueueApply($serviceAddon, 'manual'); +$executor->execute($execution); + +// Later, after a completed apply: +$removal = $executor->enqueueRemoval($serviceAddon, 'cancelled'); +$executor->execute($removal); +``` + +`enqueueApply()` and `enqueueRemoval()` return `null` when fulfilment is +disabled, the add-on has no snapshot, or a removal has no completed apply. + +## Not included in Stage 1 + +- `InvoicePaid` listener, +- `OrderService::activateOrderAddons()` integration, +- `AddonService::cancel()` integration, +- admin configuration and execution screens, +- real Proxmox, Panelica or Mail integrations, +- fixed-term expiry scheduling. diff --git a/lang/de/addons.php b/lang/de/addons.php new file mode 100644 index 000000000..c37d6c092 --- /dev/null +++ b/lang/de/addons.php @@ -0,0 +1,22 @@ + [ + 'service_or_addon_missing' => 'Der Dienst oder das Add-on existiert nicht mehr.', + 'module_not_supported' => 'Das Dienstmodul unterstützt die technische Add-on-Ausführung nicht.', + 'configuration_missing' => 'Für dieses Add-on fehlt eine vollständige Ausführungskonfiguration.', + 'validation_failed' => 'Das Modul hat die Add-on-Konfiguration abgelehnt.', + 'operation_failed' => 'Das Modul konnte die Add-on-Operation nicht ausführen.', + 'manual_required' => 'Das Modul erfordert eine manuelle Prüfung, bevor das Add-on geändert wird.', + 'invalid_service' => 'Das Add-on ist diesem Dienst nicht zugeordnet.', + 'invalid_owner' => 'Add-on und Dienst gehören nicht zum selben Kunden.', + 'not_active' => 'Dienst oder Add-on ist nicht aktiv.', + 'service_ended' => 'Der Dienst ist beendet; eine Add-on-Entfernung ist nicht nötig.', + 'unsupported_operation' => 'Das Modul unterstützt diese Add-on-Operation nicht.', + 'unsupported_parameter' => 'Das Modul unterstützt diesen Add-on-Parameter nicht.', + 'invalid_unit' => 'Die Add-on-Einheit passt nicht zu den Modulfähigkeiten.', + 'invalid_value' => 'Der Add-on-Wert ist für diese Operation ungültig.', + 'value_below_minimum' => 'Der Add-on-Wert liegt unter dem Modulminimum.', + 'value_above_maximum' => 'Der Add-on-Wert liegt über dem Modulmaximum.', + ], +]; diff --git a/lang/en/addons.php b/lang/en/addons.php new file mode 100644 index 000000000..c237627ae --- /dev/null +++ b/lang/en/addons.php @@ -0,0 +1,22 @@ + [ + 'service_or_addon_missing' => 'The service or add-on no longer exists.', + 'module_not_supported' => 'The service module does not support technical add-on execution.', + 'configuration_missing' => 'This add-on has no complete fulfillment configuration.', + 'validation_failed' => 'The module rejected the add-on configuration.', + 'operation_failed' => 'The module could not complete the add-on operation.', + 'manual_required' => 'The module requires manual review before the add-on can be changed.', + 'invalid_service' => 'The add-on is not assigned to this service.', + 'invalid_owner' => 'The add-on and service do not belong to the same client.', + 'not_active' => 'The service or add-on is not active.', + 'service_ended' => 'The service has ended; no add-on removal is needed.', + 'unsupported_operation' => 'The module does not support this add-on operation.', + 'unsupported_parameter' => 'The module does not support this add-on parameter.', + 'invalid_unit' => 'The add-on unit does not match the module capability.', + 'invalid_value' => 'The add-on value is not valid for this operation.', + 'value_below_minimum' => 'The add-on value is below the module minimum.', + 'value_above_maximum' => 'The add-on value is above the module maximum.', + ], +]; diff --git a/lang/pl/addons.php b/lang/pl/addons.php new file mode 100644 index 000000000..7ee51c38b --- /dev/null +++ b/lang/pl/addons.php @@ -0,0 +1,22 @@ + [ + 'service_or_addon_missing' => 'Usługa lub dodatek już nie istnieją.', + 'module_not_supported' => 'Moduł usługi nie obsługuje technicznej realizacji dodatków.', + 'configuration_missing' => 'Ten dodatek nie ma kompletnej konfiguracji realizacji.', + 'validation_failed' => 'Moduł odrzucił konfigurację dodatku.', + 'operation_failed' => 'Moduł nie mógł wykonać operacji dodatku.', + 'manual_required' => 'Moduł wymaga ręcznej weryfikacji przed zmianą dodatku.', + 'invalid_service' => 'Dodatek nie jest przypisany do tej usługi.', + 'invalid_owner' => 'Dodatek i usługa nie należą do tego samego klienta.', + 'not_active' => 'Usługa lub dodatek nie są aktywne.', + 'service_ended' => 'Usługa została zakończona; usuwanie dodatku nie jest potrzebne.', + 'unsupported_operation' => 'Moduł nie obsługuje tej operacji dodatku.', + 'unsupported_parameter' => 'Moduł nie obsługuje tego parametru dodatku.', + 'invalid_unit' => 'Jednostka dodatku nie zgadza się z możliwościami modułu.', + 'invalid_value' => 'Wartość dodatku jest nieprawidłowa dla tej operacji.', + 'value_below_minimum' => 'Wartość dodatku jest poniżej minimum modułu.', + 'value_above_maximum' => 'Wartość dodatku jest powyżej maksimum modułu.', + ], +]; diff --git a/lang/tr/addons.php b/lang/tr/addons.php new file mode 100644 index 000000000..88fdce0e0 --- /dev/null +++ b/lang/tr/addons.php @@ -0,0 +1,22 @@ + [ + 'service_or_addon_missing' => 'Hizmet veya eklenti artık mevcut değil.', + 'module_not_supported' => 'Hizmet modülü teknik eklenti uygulamasını desteklemiyor.', + 'configuration_missing' => 'Bu eklenti için tam bir uygulama yapılandırması yok.', + 'validation_failed' => 'Modül eklenti yapılandırmasını reddetti.', + 'operation_failed' => 'Modül eklenti işlemini tamamlayamadı.', + 'manual_required' => 'Modül, eklenti değiştirilmeden önce manuel inceleme istiyor.', + 'invalid_service' => 'Eklenti bu hizmete atanmamış.', + 'invalid_owner' => 'Eklenti ve hizmet aynı müşteriye ait değil.', + 'not_active' => 'Hizmet veya eklenti etkin değil.', + 'service_ended' => 'Hizmet sona erdi; eklentiyi kaldırmak gerekmiyor.', + 'unsupported_operation' => 'Modül bu eklenti işlemini desteklemiyor.', + 'unsupported_parameter' => 'Modül bu eklenti parametresini desteklemiyor.', + 'invalid_unit' => 'Eklenti birimi modül yetenekleriyle eşleşmiyor.', + 'invalid_value' => 'Eklenti değeri bu işlem için geçersiz.', + 'value_below_minimum' => 'Eklenti değeri modül minimumunun altında.', + 'value_above_maximum' => 'Eklenti değeri modül maksimumunun üzerinde.', + ], +]; diff --git a/lang/zh/addons.php b/lang/zh/addons.php new file mode 100644 index 000000000..671d82f22 --- /dev/null +++ b/lang/zh/addons.php @@ -0,0 +1,22 @@ + [ + 'service_or_addon_missing' => '服务或附加项已不存在。', + 'module_not_supported' => '服务模块不支持附加项的技术执行。', + 'configuration_missing' => '此附加项缺少完整的执行配置。', + 'validation_failed' => '模块拒绝了附加项配置。', + 'operation_failed' => '模块无法完成附加项操作。', + 'manual_required' => '模块需要人工审核后才能更改附加项。', + 'invalid_service' => '附加项未分配到此服务。', + 'invalid_owner' => '附加项和服务不属于同一客户。', + 'not_active' => '服务或附加项未处于活动状态。', + 'service_ended' => '服务已结束,无需移除附加项。', + 'unsupported_operation' => '模块不支持此附加项操作。', + 'unsupported_parameter' => '模块不支持此附加项参数。', + 'invalid_unit' => '附加项单位与模块能力不匹配。', + 'invalid_value' => '此操作中的附加项值无效。', + 'value_below_minimum' => '附加项值低于模块最小值。', + 'value_above_maximum' => '附加项值高于模块最大值。', + ], +]; diff --git a/mkdocs.yml b/mkdocs.yml index f49a9c5f9..ec2daa369 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -130,6 +130,7 @@ nav: - Setup: mcp/index.md - Tools: mcp/tools.md - Developer: + - Add-on executor: developer/addon-executor.md - Overview: developer/index.md - Writing a Module: developer/modules.md - Hooks: developer/hooks.md diff --git a/modules/Servers/AddonTest/AddonTestModule.php b/modules/Servers/AddonTest/AddonTestModule.php new file mode 100644 index 000000000..4ead1d6bd --- /dev/null +++ b/modules/Servers/AddonTest/AddonTestModule.php @@ -0,0 +1,250 @@ +assertAvailable(); + + return [ + 'operations' => ['increment', 'decrement', 'set', 'attach', 'detach'], + 'parameters' => [ + 'storage_quota' => ['unit' => 'GB', 'min' => 0], + 'extra_feature' => ['unit' => null], + ], + ]; + } + + public function validateAddon(Service $service, AddonInstruction $instruction): array + { + $this->assertAvailable(); + + if (! in_array($instruction->operation, $this->addonCapabilities()['operations'], true)) { + return $this->result(false, 'Unsupported test operation'); + } + + if (! is_numeric($instruction->value) && in_array($instruction->operation, ['increment', 'decrement', 'set'], true)) { + return $this->result(false, 'A numeric value is required'); + } + + return $this->result(true, 'Test add-on can be applied'); + } + + public function applyAddon(Service $service, AddonInstruction $instruction): array + { + $this->assertAvailable(); + + $data = $this->data($service); + if (isset($data['executions'][$instruction->executionId])) { + return $this->result(true, 'Test add-on already applied', [ + 'idempotent' => true, + 'execution' => $data['executions'][$instruction->executionId], + ]); + } + + $simulate = (string) ($instruction->options['simulate'] ?? ''); + + if ($simulate === 'fail_permanent') { + return $this->result(false, 'Simulated permanent failure', ['retryable' => false]); + } + + if ($simulate === 'fail_once') { + $key = 'addon_test:fail_once:'.$instruction->executionId; + if (! Cache::get($key)) { + Cache::put($key, true, 3600); + + return $this->result(false, 'Simulated transient failure', ['retryable' => true]); + } + } + + if ($simulate === 'manual_required') { + return $this->result(false, 'Simulated manual review required', ['manual_required' => true]); + } + + if ($instruction->operation === 'decrement' && (float) $instruction->value > (float) ($data['state'][$instruction->parameter] ?? 0)) { + return $this->result(false, 'Refusing to reduce below the current test value', ['retryable' => false]); + } + + $previous = $data['state'][$instruction->parameter] ?? null; + $current = $this->nextValue($instruction, $previous); + + $data['state'][$instruction->parameter] = $current; + $data['executions'][$instruction->executionId] = [ + 'action' => 'apply', + 'operation' => $instruction->operation, + 'parameter' => $instruction->parameter, + 'value' => $instruction->value, + 'unit' => $instruction->unit, + 'previous' => $previous, + 'current' => $current, + 'at' => now()->toIso8601String(), + ]; + + $service->forceFill(['module_data' => $this->withData($service, $data)])->save(); + + return $this->result(true, 'Test add-on applied', [ + 'previous' => $previous, + 'current' => $current, + ]); + } + + public function removeAddon(Service $service, AddonInstruction $instruction): array + { + $this->assertAvailable(); + + $data = $this->data($service); + $applied = $data['executions'][$instruction->appliedExecutionId ?? $instruction->executionId] ?? null; + + if (! $applied) { + return $this->result(true, 'Test add-on was not applied', ['idempotent' => true]); + } + + $simulate = (string) ($instruction->options['simulate'] ?? ''); + if ($simulate === 'refuse_remove' || ! empty($applied['refuse_remove'])) { + return $this->result(false, 'Simulated refusal to remove the add-on', ['manual_required' => true]); + } + + $parameter = (string) $applied['parameter']; + $previous = $applied['previous'] ?? null; + + if ($previous === null) { + unset($data['state'][$parameter]); + } else { + $data['state'][$parameter] = $previous; + } + + $applied['action'] = 'remove'; + $applied['removed_at'] = now()->toIso8601String(); + $data['executions'][$instruction->executionId] = $applied; + + $service->forceFill(['module_data' => $this->withData($service, $data)])->save(); + + return $this->result(true, 'Test add-on removed', ['previous' => $previous]); + } + + public function getAddonStatus(Service $service, AddonInstruction $instruction): array + { + $this->assertAvailable(); + + $data = $this->data($service); + $applied = $data['executions'][$instruction->appliedExecutionId ?? $instruction->executionId] ?? null; + + return $this->result((bool) $applied, $applied ? 'Test add-on is present' : 'Test add-on is absent', [ + 'applied' => (bool) $applied, + 'state' => $data['state'][$instruction->parameter] ?? null, + ]); + } + + public function listPackages(Server $server): array + { + return []; + } + + public function create(Service $service): array + { + return $this->result(true, 'Test service created'); + } + + public function suspend(Service $service, string $reason = ''): array + { + return $this->result(true, 'Test service suspended'); + } + + public function unsuspend(Service $service): array + { + return $this->result(true, 'Test service unsuspended'); + } + + public function terminate(Service $service): array + { + return $this->result(true, 'Test service terminated'); + } + + public function changePassword(Service $service, string $newPassword): array + { + return $this->result(true, 'Test password changed'); + } + + public function changePackage(Service $service, array $newPackage): array + { + return $this->result(true, 'Test package changed'); + } + + public function usageUpdate(Server $server): array + { + return ['updated' => 0, 'errors' => 0]; + } + + public function testConnection(Server $server): bool + { + return true; + } + + public function getConfigFields(): array + { + return []; + } + + private function assertAvailable(): void + { + if (! app()->environment(['local', 'testing']) + || ! config('addons.fulfillment.test_module_enabled', false)) { + throw new RuntimeException('The AddonTest module is only available in local/testing.'); + } + } + + private function data(Service $service): array + { + $data = $service->module_data ?? []; + + return [ + 'state' => is_array($data['addon_test']['state'] ?? null) ? $data['addon_test']['state'] : [], + 'executions' => is_array($data['addon_test']['executions'] ?? null) ? $data['addon_test']['executions'] : [], + ]; + } + + private function withData(Service $service, array $data): array + { + $moduleData = $service->module_data ?? []; + $moduleData['addon_test'] = $data; + + return $moduleData; + } + + private function nextValue(AddonInstruction $instruction, mixed $previous): mixed + { + return match ($instruction->operation) { + 'increment' => (float) ($previous ?? 0) + (float) $instruction->value, + 'decrement' => (float) ($previous ?? 0) - (float) $instruction->value, + 'set' => $instruction->value, + 'attach', 'detach' => $instruction->value, + default => $previous, + }; + } + + private function result(bool $success, string $message, array $data = []): array + { + return compact('success', 'message', 'data'); + } +} diff --git a/routes/console.php b/routes/console.php index 7468936f9..abbe15c1f 100644 --- a/routes/console.php +++ b/routes/console.php @@ -100,6 +100,9 @@ // Module queue — retry failed provisioning actions every 5 minutes Schedule::command('pnlcs:module-queue')->everyFiveMinutes()->withoutOverlapping(); +// Add-on fulfilment — retry pending/failed technical executions every 5 minutes +Schedule::command('pnlcs:addon-executions:process')->everyFiveMinutes()->withoutOverlapping(); + // Panelica licenses: find the servers customers installed with their link and // buy the license (nothing to do, one query, while no service is waiting). Schedule::command('pnlcs:panelica-licenses')->everyFiveMinutes()->withoutOverlapping(10); diff --git a/tests/Feature/AddonExecutorTest.php b/tests/Feature/AddonExecutorTest.php new file mode 100644 index 000000000..32fc03080 --- /dev/null +++ b/tests/Feature/AddonExecutorTest.php @@ -0,0 +1,329 @@ +set('addons.fulfillment.enabled', true); + config()->set('addons.fulfillment.test_module_enabled', true); + Queue::fake(); + app(ModuleRegistry::class)->registerServer('addon_test', AddonTestModule::class); +}); + +function addonTestService(string $status = 'active', string $module = 'addon_test'): Service +{ + $client = Client::factory()->create(); + $product = Product::factory()->create(['server_type' => $module]); + + return Service::factory()->create([ + 'client_id' => $client->id, + 'product_id' => $product->id, + 'status' => $status, + 'module_data' => [], + ]); +} + +function addonTestProductAddon(array $config = []): ProductAddon +{ + return ProductAddon::create(array_merge([ + 'name' => 'Test storage', + 'auto_fulfill' => true, + 'operation' => 'increment', + 'parameter' => 'storage_quota', + 'value' => '50', + 'unit' => 'GB', + 'options' => [], + ], $config)); +} + +function addonTestServiceAddon( + Service $service, + ?ProductAddon $productAddon = null, + array $overrides = [] +): ServiceAddon { + $productAddon ??= addonTestProductAddon(); + $config = $productAddon->fulfillmentConfig(); + + return ServiceAddon::create(array_merge([ + 'service_id' => $service->id, + 'addon_id' => $productAddon->id, + 'client_id' => $service->client_id, + 'qty' => 1, + 'amount' => 10, + 'billing_cycle' => 'Monthly', + 'status' => 'active', + 'fulfillment_config' => $config, + 'fulfillment_status' => AddonExecutionStatus::NotConfigured, + ], $overrides)); +} + +it('does nothing when the fulfillment feature flag is off', function () { + config()->set('addons.fulfillment.enabled', false); + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + + expect(app(AddonExecutionService::class)->enqueueApply($addon))->toBeNull() + ->and(ServiceAddonExecution::count())->toBe(0); +}); + +it('applies an addon through the test module and records the attempt', function () { + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + + $execution = app(AddonExecutionService::class)->enqueueApply($addon, 'test'); + expect($execution)->not->toBeNull(); + + expect(app(AddonExecutionService::class)->execute($execution))->toBeTrue(); + + $execution->refresh(); + $addon->refresh(); + + expect($execution->status)->toBe(AddonExecutionStatus::Completed) + ->and($execution->attempts)->toBe(1) + ->and($addon->fulfillment_status)->toBe(AddonExecutionStatus::Completed) + ->and($addon->fulfilled_at)->not->toBeNull() + ->and((float) $service->fresh()->module_data['addon_test']['state']['storage_quota'])->toBe(50.0) + ->and(ServiceAddonExecutionAttempt::where('execution_id', $execution->id)->count())->toBe(1); +}); + +it('keeps one execution and one effect when apply is requested twice', function () { + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + + $first = $executor->enqueueApply($addon, 'first'); + $executor->execute($first); + $second = $executor->enqueueApply($addon, 'second'); + + expect($second->id)->toBe($first->id) + ->and(ServiceAddonExecution::count())->toBe(1) + ->and($executor->execute($second->fresh()))->toBeFalse() + ->and(ServiceAddonExecutionAttempt::where('execution_id', $first->id)->count())->toBe(1); +}); + +it('rejects an invalid numeric value before calling the module', function () { + $service = addonTestService(); + $productAddon = addonTestProductAddon(['value' => 'not-a-number']); + $addon = addonTestServiceAddon($service, $productAddon); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + expect($execution->fresh()->status)->toBe(AddonExecutionStatus::Failed) + ->and($execution->fresh()->result_message)->toContain('value') + ->and($service->fresh()->module_data)->toBe([]); +}); + +it('rejects a service and addon owned by different clients', function () { + $service = addonTestService(); + $otherClient = Client::factory()->create(); + $addon = addonTestServiceAddon($service, null, ['client_id' => $otherClient->id]); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + expect($execution->fresh()->status)->toBe(AddonExecutionStatus::Failed) + ->and($execution->fresh()->result_message)->toContain('client'); +}); + +it('marks a module without the addon contract as unsupported', function () { + $service = addonTestService('active', 'custom'); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + expect($execution->fresh()->status)->toBe(AddonExecutionStatus::Unsupported); +}); + +it('retries a transient module failure with a new attempt record', function () { + $service = addonTestService(); + $productAddon = addonTestProductAddon(['options' => ['simulate' => 'fail_once']]); + $addon = addonTestServiceAddon($service, $productAddon); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + expect($execution->fresh()->status)->toBe(AddonExecutionStatus::Retry) + ->and($execution->fresh()->attempts)->toBe(1) + ->and(ServiceAddonExecutionAttempt::where('execution_id', $execution->id)->count())->toBe(1); + + expect($executor->retry($execution->fresh()))->toBeTrue(); + + expect($execution->fresh()->status)->toBe(AddonExecutionStatus::Completed) + ->and($execution->fresh()->attempts)->toBe(2) + ->and(ServiceAddonExecutionAttempt::where('execution_id', $execution->id)->count())->toBe(2); +}); + +it('does not retry a permanent module failure', function () { + $service = addonTestService(); + $productAddon = addonTestProductAddon(['options' => ['simulate' => 'fail_permanent']]); + $addon = addonTestServiceAddon($service, $productAddon); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + expect($execution->fresh()->status)->toBe(AddonExecutionStatus::Failed) + ->and($execution->fresh()->attempts)->toBe(1); +}); + +it('removes a completed addon and marks the technical status cancelled', function () { + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + + $apply = $executor->enqueueApply($addon); + $executor->execute($apply); + $remove = $executor->enqueueRemoval($addon->fresh()); + $executor->execute($remove); + + expect($remove->fresh()->action)->toBe(AddonExecutionAction::Remove) + ->and($remove->fresh()->status)->toBe(AddonExecutionStatus::Completed) + ->and($addon->fresh()->fulfillment_status)->toBe(AddonExecutionStatus::Cancelled) + ->and($service->fresh()->module_data['addon_test']['state'])->not->toHaveKey('storage_quota'); +}); + +it('turns a refused removal into manual_required and keeps the effect', function () { + $service = addonTestService(); + $productAddon = addonTestProductAddon(['options' => ['simulate' => 'refuse_remove']]); + $addon = addonTestServiceAddon($service, $productAddon); + $executor = app(AddonExecutionService::class); + + $apply = $executor->enqueueApply($addon); + $executor->execute($apply); + $remove = $executor->enqueueRemoval($addon->fresh()); + $executor->execute($remove); + + expect($remove->fresh()->status)->toBe(AddonExecutionStatus::ManualRequired) + ->and($addon->fresh()->fulfillment_status)->toBe(AddonExecutionStatus::ManualRequired) + ->and((float) $service->fresh()->module_data['addon_test']['state']['storage_quota'])->toBe(50.0); +}); + +it('does not execute a completed execution twice and refuses retry of completed', function () { + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + expect($executor->execute($execution->fresh()))->toBeFalse() + ->and($executor->retry($execution->fresh()))->toBeFalse() + ->and(ServiceAddonExecutionAttempt::where('execution_id', $execution->id)->count())->toBe(1); +}); + +it('does not enqueue an addon without a fulfillment snapshot', function () { + $service = addonTestService(); + $productAddon = addonTestProductAddon(); + $addon = addonTestServiceAddon($service, $productAddon, ['fulfillment_config' => null]); + + expect(app(AddonExecutionService::class)->enqueueApply($addon))->toBeNull() + ->and(ServiceAddonExecution::count())->toBe(0); +}); + +it('rejects an unsupported parameter before calling the module', function () { + $service = addonTestService(); + $productAddon = addonTestProductAddon(['parameter' => 'not_supported']); + $addon = addonTestServiceAddon($service, $productAddon); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + expect($execution->fresh()->status)->toBe(AddonExecutionStatus::Unsupported) + ->and($service->fresh()->module_data)->toBe([]); +}); + +it('rejects a unit that does not match the module capability', function () { + $service = addonTestService(); + $productAddon = addonTestProductAddon(['unit' => 'MB']); + $addon = addonTestServiceAddon($service, $productAddon); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + expect($execution->fresh()->status)->toBe(AddonExecutionStatus::Failed) + ->and($service->fresh()->module_data)->toBe([]); +}); + +it('records a failed attempt with its error', function () { + $service = addonTestService(); + $productAddon = addonTestProductAddon(['value' => 'bad']); + $addon = addonTestServiceAddon($service, $productAddon); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + $attempt = ServiceAddonExecutionAttempt::where('execution_id', $execution->id)->firstOrFail(); + + expect($attempt->attempt_no)->toBe(1) + ->and($attempt->status)->toBe(AddonExecutionStatus::Failed) + ->and($attempt->error)->not->toBeNull() + ->and($attempt->started_at)->not->toBeNull() + ->and($attempt->finished_at)->not->toBeNull(); +}); + +it('processes a due execution from the scheduler command', function () { + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + $execution = $executor->enqueueApply($addon); + + $this->artisan('pnlcs:addon-executions:process', ['--id' => $execution->id]) + ->assertSuccessful(); + + expect($execution->fresh()->status)->toBe(AddonExecutionStatus::Completed); +}); + +it('refuses the test module when its configuration is disabled', function () { + config()->set('addons.fulfillment.test_module_enabled', false); + + expect(fn () => (new AddonTestModule)->addonCapabilities()) + ->toThrow(RuntimeException::class); +}); + + +it('removes using the applied configuration snapshot, not a later edit', function () { + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + + $apply = $executor->enqueueApply($addon); + $executor->execute($apply); + + $addon->update([ + 'fulfillment_config' => [ + 'operation' => 'set', + 'parameter' => 'storage_quota', + 'value' => '999', + 'unit' => 'GB', + 'options' => [], + 'auto_fulfill' => true, + ], + ]); + + $remove = $executor->enqueueRemoval($addon->fresh()); + $executor->execute($remove); + + expect($remove->fresh()->status)->toBe(AddonExecutionStatus::Completed) + ->and(data_get($remove->fresh()->request_payload, 'configuration.value'))->toBe('50') + ->and($service->fresh()->module_data['addon_test']['state'])->not->toHaveKey('storage_quota'); +}); diff --git a/tests/Feature/ModuleCompletenessTest.php b/tests/Feature/ModuleCompletenessTest.php index 4dc5482a4..8a2556728 100644 --- a/tests/Feature/ModuleCompletenessTest.php +++ b/tests/Feature/ModuleCompletenessTest.php @@ -25,6 +25,10 @@ function registeredServerModules(): array test('every module folder is registered', function () { $onDisk = collect(glob(base_path('modules/Servers/*'), GLOB_ONLYDIR)) ->map(fn ($dir) => strtolower(basename($dir))) + // AddonTest is a deliberately manifest-less, local/testing-only module + // for the Addon Executor foundation. It must not be discovered in + // production; see docs/developer/addon-executor.md. + ->reject(fn (string $name) => $name === 'addontest') ->values() ->all(); From da7ff2bb2eb5bfd7bcde083d44073a4dc76340f4 Mon Sep 17 00:00:00 2001 From: Grzegorz Date: Sun, 29 Nov 2026 15:16:42 +0100 Subject: [PATCH 2/2] fix(addons): harden executor claims and secret handling --- .env.example | 1 + .../ProcessAddonExecutionsCommand.php | 5 + .../AddonModuleUnavailableException.php | 7 + app/Models/ServiceAddonExecution.php | 2 +- app/Services/Addons/AddonExecutionService.php | 225 +++++++++++--- app/Support/Addons/AddonPayloadSanitizer.php | 99 ++++++ config/addons.php | 3 + ...laim_token_to_service_addon_executions.php | 24 ++ docs/developer/addon-executor.md | 62 +++- lang/de/addons.php | 3 + lang/en/addons.php | 3 + lang/pl/addons.php | 3 + lang/tr/addons.php | 3 + lang/zh/addons.php | 3 + modules/Servers/AddonTest/AddonTestModule.php | 24 +- tests/Feature/AddonExecutorTest.php | 287 +++++++++++++++++- tests/Feature/ScheduledCommandsTest.php | 2 +- 17 files changed, 707 insertions(+), 49 deletions(-) create mode 100644 app/Exceptions/AddonModuleUnavailableException.php create mode 100644 app/Support/Addons/AddonPayloadSanitizer.php create mode 100644 database/migrations/2026_11_30_000005_add_claim_token_to_service_addon_executions.php diff --git a/.env.example b/.env.example index a508f442e..38981def4 100644 --- a/.env.example +++ b/.env.example @@ -40,6 +40,7 @@ DB_PASSWORD= # Off by default. This only controls the technical add-on executor; sales, # invoicing and billing are unaffected. ADDONS_FULFILLMENT_ENABLED=false +ADDONS_FULFILLMENT_PROCESSING_TIMEOUT=15 # The AddonTest module is only registered in local/testing, and only when # this is on. Never enable it in production. ADDONS_TEST_MODULE_ENABLED=false diff --git a/app/Console/Commands/ProcessAddonExecutionsCommand.php b/app/Console/Commands/ProcessAddonExecutionsCommand.php index 91ca07b6a..1f8fcc063 100644 --- a/app/Console/Commands/ProcessAddonExecutionsCommand.php +++ b/app/Console/Commands/ProcessAddonExecutionsCommand.php @@ -21,6 +21,11 @@ public function handle(AddonExecutionService $executor): int return self::SUCCESS; } + $reclaimed = $executor->reclaimStale(max(1, (int) $this->option('limit'))); + if ($reclaimed > 0) { + $this->info('Reclaimed '.$reclaimed.' stale execution(s).'); + } + $query = ServiceAddonExecution::query() ->whereIn('status', [ AddonExecutionStatus::Pending->value, diff --git a/app/Exceptions/AddonModuleUnavailableException.php b/app/Exceptions/AddonModuleUnavailableException.php new file mode 100644 index 000000000..b28f9a596 --- /dev/null +++ b/app/Exceptions/AddonModuleUnavailableException.php @@ -0,0 +1,7 @@ +assertNoSecrets($config); + return $this->enqueue($addon, AddonExecutionAction::Apply, $config, $reason, $invoice); } @@ -69,14 +78,9 @@ public function enqueueRemoval(ServiceAddon $addon, string $reason = 'cancelled' return null; } - return $this->enqueue( - $addon, - AddonExecutionAction::Remove, - $config, - $reason, - null, - $applied->id - ); + $this->assertNoSecrets($config); + + return $this->enqueue($addon, AddonExecutionAction::Remove, $config, $reason, null, $applied->id); } public function execute(ServiceAddonExecution $execution): bool @@ -85,11 +89,14 @@ public function execute(ServiceAddonExecution $execution): bool return false; } + $claimToken = Str::random(64); + $claimed = ServiceAddonExecution::query() ->whereKey($execution->id) ->whereIn('status', [AddonExecutionStatus::Pending->value, AddonExecutionStatus::Retry->value]) ->update([ 'status' => AddonExecutionStatus::Processing->value, + 'claim_token' => $claimToken, 'started_at' => now(), 'finished_at' => null, 'attempts' => DB::raw('attempts + 1'), @@ -113,12 +120,12 @@ public function execute(ServiceAddonExecution $execution): bool $service = $execution->service; if (! $addon || ! $service) { - return $this->finish($execution, AddonExecutionStatus::Failed, null, __('addons.executor.service_or_addon_missing'), null, $attempt); + return $this->finish($execution, AddonExecutionStatus::Failed, null, __('addons.executor.service_or_addon_missing'), null, $attempt, $claimToken); } $problem = $this->validateExecution($execution, $addon, $service); if ($problem !== null) { - return $this->finish($execution, $problem['status'], null, $problem['message'], null, $attempt); + return $this->finish($execution, $problem['status'], null, $problem['message'], null, $attempt, $claimToken); } $module = $this->provisioning->resolveModule($service); @@ -130,7 +137,8 @@ public function execute(ServiceAddonExecution $execution): bool null, __('addons.executor.module_not_supported'), null, - $attempt + $attempt, + $claimToken ); } @@ -140,12 +148,14 @@ public function execute(ServiceAddonExecution $execution): bool } if ($config === null || ! is_array($config)) { - return $this->finish($execution, AddonExecutionStatus::Failed, null, __('addons.executor.configuration_missing'), null, $attempt); + return $this->finish($execution, AddonExecutionStatus::Failed, null, __('addons.executor.configuration_missing'), null, $attempt, $claimToken); } + $this->assertNoSecrets($config); + $problem = $this->validateCapabilities($module, $config); if ($problem !== null) { - return $this->finish($execution, $problem['status'], null, $problem['message'], null, $attempt); + return $this->finish($execution, $problem['status'], null, $problem['message'], null, $attempt, $claimToken); } $instruction = $this->instruction($execution, $addon, $config); @@ -158,7 +168,8 @@ public function execute(ServiceAddonExecution $execution): bool $validation, (string) ($validation['message'] ?? __('addons.executor.validation_failed')), null, - $attempt + $attempt, + $claimToken ); } @@ -177,7 +188,8 @@ public function execute(ServiceAddonExecution $execution): bool $result, (string) ($result['message'] ?? __('addons.executor.manual_required')), null, - $attempt + $attempt, + $claimToken ); } @@ -190,27 +202,44 @@ public function execute(ServiceAddonExecution $execution): bool $status, $result, (string) ($result['message'] ?? __('addons.executor.operation_failed')), - $status === AddonExecutionStatus::Retry ? now()->addMinutes(5 * (2 ** max(0, $execution->attempts - 1))) : null, - $attempt + $status === AddonExecutionStatus::Retry ? $this->nextAttemptAt($execution) : null, + $attempt, + $claimToken ); } - return $this->finish($execution, AddonExecutionStatus::Completed, $result, (string) ($result['message'] ?? ''), null, $attempt); + return $this->finish($execution, AddonExecutionStatus::Completed, $result, (string) ($result['message'] ?? ''), null, $attempt, $claimToken); + } catch (AddonModuleUnavailableException $e) { + return $this->finish( + $execution, + AddonExecutionStatus::Unsupported, + null, + $this->sanitizer->sanitizeText($e->getMessage()), + null, + $attempt, + $claimToken + ); } catch (Throwable $e) { Log::error('AddonExecutionService::execute failed', [ 'execution_id' => $execution->id, 'service_addon_id' => $execution->service_addon_id, - 'error' => $e->getMessage(), + 'exception' => $e::class, + 'error' => $this->sanitizer->sanitizeText($e->getMessage()), ]); $status = $execution->attempts < $execution->max_attempts ? AddonExecutionStatus::Retry : AddonExecutionStatus::Failed; - $availableAt = $status === AddonExecutionStatus::Retry - ? now()->addMinutes(5 * (2 ** max(0, $execution->attempts - 1))) - : null; - return $this->finish($execution, $status, null, $e->getMessage(), $availableAt, $attempt); + return $this->finish( + $execution, + $status, + null, + $this->sanitizer->sanitizeText($e->getMessage()), + $status === AddonExecutionStatus::Retry ? $this->nextAttemptAt($execution) : null, + $attempt, + $claimToken + ); } } @@ -226,6 +255,7 @@ public function retry(ServiceAddonExecution $execution): bool $execution->forceFill([ 'status' => AddonExecutionStatus::Retry, + 'claim_token' => null, 'available_at' => now(), 'finished_at' => null, 'result_message' => null, @@ -234,6 +264,62 @@ public function retry(ServiceAddonExecution $execution): bool return $this->execute($execution->fresh()); } + /** + * Reclaim executions whose worker died after claiming them. The old + * worker cannot write its result because every finish is tied to the + * claim token it received. + */ + public function reclaimStale(int $limit = 25): int + { + if (! $this->enabled()) { + return 0; + } + + $timeout = max(1, (int) config('addons.fulfillment.processing_timeout_minutes', 15)); + $cutoff = now()->subMinutes($timeout); + $reclaimed = 0; + + $executions = ServiceAddonExecution::query() + ->where('status', AddonExecutionStatus::Processing->value) + ->where('started_at', '<=', $cutoff) + ->limit(max(1, $limit)) + ->get(); + + foreach ($executions as $execution) { + $token = $execution->claim_token; + + $updated = ServiceAddonExecution::query() + ->whereKey($execution->id) + ->where('status', AddonExecutionStatus::Processing->value) + ->where('started_at', '<=', $cutoff) + ->where('claim_token', $token) + ->update([ + 'status' => AddonExecutionStatus::Retry->value, + 'claim_token' => null, + 'available_at' => now(), + 'finished_at' => null, + 'result_message' => __('addons.executor.lease_expired'), + ]); + + if ($updated === 0) { + continue; + } + + ServiceAddonExecutionAttempt::query() + ->where('execution_id', $execution->id) + ->where('status', AddonExecutionStatus::Processing->value) + ->update([ + 'status' => AddonExecutionStatus::Cancelled->value, + 'error' => __('addons.executor.lease_expired'), + 'finished_at' => now(), + ]); + + $reclaimed++; + } + + return $reclaimed; + } + private function enqueue( ServiceAddon $addon, AddonExecutionAction $action, @@ -261,23 +347,36 @@ private function enqueue( 'parameter' => $config['parameter'] ?? null, 'value' => isset($config['value']) ? (string) $config['value'] : null, 'unit' => $config['unit'] ?? null, - 'request_payload' => [ + 'request_payload' => $this->sanitizer->sanitize([ 'reason' => $reason, 'configuration' => $config, 'configuration_hash' => $hash, 'applied_execution_id' => $appliedExecutionId, - ], + ]), 'max_attempts' => self::MAX_ATTEMPTS, ] ); - if (in_array($execution->status, [AddonExecutionStatus::Pending, AddonExecutionStatus::Retry], true)) { - DB::afterCommit(fn () => ExecuteServiceAddonJob::dispatch($execution->id)); - } + $this->dispatchIfDue($execution); return $execution; } + private function dispatchIfDue(ServiceAddonExecution $execution): void + { + if (! in_array($execution->status, [AddonExecutionStatus::Pending, AddonExecutionStatus::Retry], true)) { + return; + } + + if ($execution->status === AddonExecutionStatus::Retry + && $execution->available_at !== null + && $execution->available_at->isFuture()) { + return; + } + + DB::afterCommit(fn () => ExecuteServiceAddonJob::dispatch($execution->id)); + } + /** * @return array|null */ @@ -297,6 +396,13 @@ private function configuration(ServiceAddon $addon): ?array return $config; } + private function assertNoSecrets(array $config): void + { + if ($this->sanitizer->containsSensitiveKeys($config)) { + throw new InvalidArgumentException(__('addons.executor.secret_not_allowed')); + } + } + /** * @return array{status: AddonExecutionStatus, message: string}|null */ @@ -393,41 +499,72 @@ private function finish( ?array $result, string $message, ?\DateTimeInterface $availableAt = null, - ?ServiceAddonExecutionAttempt $attempt = null + ?ServiceAddonExecutionAttempt $attempt = null, + ?string $claimToken = null ): bool { $terminal = $status->isFinished(); - $error = $status === AddonExecutionStatus::Completed ? null : $message; + $cleanMessage = $this->sanitizer->sanitizeText($message); + $cleanData = $this->sanitizer->sanitize($result['data'] ?? []); + $error = $status === AddonExecutionStatus::Completed ? null : $cleanMessage; + + $written = DB::transaction(function () use ($execution, $status, $cleanData, $cleanMessage, $availableAt, $attempt, $claimToken, $terminal, $error): bool { + $updated = ServiceAddonExecution::query() + ->whereKey($execution->id) + ->where('status', AddonExecutionStatus::Processing->value) + ->where('claim_token', $claimToken) + ->update([ + 'status' => $status->value, + 'claim_token' => $status === AddonExecutionStatus::Processing ? $claimToken : null, + 'response_payload' => $cleanData, + 'result_message' => $cleanMessage, + 'available_at' => $availableAt, + 'finished_at' => $terminal ? now() : null, + ]); + + if ($updated === 0) { + if ($attempt) { + $attempt->forceFill([ + 'status' => AddonExecutionStatus::Cancelled, + 'error' => __('addons.executor.claim_superseded'), + 'finished_at' => now(), + ])->save(); + } - DB::transaction(function () use ($execution, $status, $result, $message, $availableAt, $attempt, $terminal, $error): void { - $execution->forceFill([ - 'status' => $status, - 'response_payload' => $result['data'] ?? [], - 'result_message' => $message, - 'available_at' => $availableAt, - 'finished_at' => $terminal ? now() : null, - ])->save(); + return false; + } + + $execution->refresh(); if ($attempt) { $attempt->forceFill([ 'status' => $status, - 'response_payload' => $result['data'] ?? [], + 'response_payload' => $cleanData, 'error' => $error, 'finished_at' => now(), ])->save(); } - if ($execution->serviceAddon) { - $execution->serviceAddon->forceFill([ + $addon = $execution->serviceAddon; + + if ($addon) { + $addon->forceFill([ 'fulfillment_status' => $status === AddonExecutionStatus::Completed && $execution->action === AddonExecutionAction::Remove ? AddonExecutionStatus::Cancelled : $status, - 'fulfilled_at' => $status === AddonExecutionStatus::Completed ? now() : $execution->serviceAddon->fulfilled_at, + 'fulfilled_at' => $status === AddonExecutionStatus::Completed ? now() : $addon->fulfilled_at, 'fulfillment_error' => $error, ])->save(); } + + return true; }); - return $status === AddonExecutionStatus::Completed; + return $written && $status === AddonExecutionStatus::Completed; + } + + private function nextAttemptAt(ServiceAddonExecution $execution): \DateTimeInterface + { + return now()->addMinutes(5 * (2 ** max(0, $execution->attempts - 1))); } /** diff --git a/app/Support/Addons/AddonPayloadSanitizer.php b/app/Support/Addons/AddonPayloadSanitizer.php new file mode 100644 index 000000000..eca729cd5 --- /dev/null +++ b/app/Support/Addons/AddonPayloadSanitizer.php @@ -0,0 +1,99 @@ +containsSensitiveKeys($decoded); + } + + return false; + } + + if (! is_array($value)) { + return false; + } + + foreach ($value as $key => $child) { + if (is_string($key) && $this->isSensitiveKey($key)) { + return true; + } + + if ($this->containsSensitiveKeys($child)) { + return true; + } + } + + return false; + } + + public function sanitize(mixed $value): mixed + { + if (is_string($value)) { + $decoded = json_decode($value, true); + if (is_array($decoded)) { + return json_encode($this->sanitize($decoded), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); + } + + return $this->sanitizeText($value); + } + + if (! is_array($value)) { + return $value; + } + + $clean = []; + + foreach ($value as $key => $child) { + if (is_string($key) && $this->isSensitiveKey($key)) { + $clean[$key] = '[redacted]'; + + continue; + } + + $clean[$key] = $this->sanitize($child); + } + + return $clean; + } + + public function sanitizeText(string $text): string + { + $keys = implode('|', array_map(fn (string $key): string => preg_quote($key, '/'), self::SENSITIVE_KEYS)); + + $text = preg_replace('/\b('.$keys.'|api[_-]?key|client[_-]?secret)\b\s*[:=]\s*[^\s,;]+/iu', '$1=[redacted]', $text) ?? $text; + $text = preg_replace('/\bBearer\s+[A-Za-z0-9._~+\/=-]+/iu', 'Bearer [redacted]', $text) ?? $text; + + return $text; + } + + private function isSensitiveKey(string $key): bool + { + $normalized = preg_replace('/[^a-z0-9]/', '', strtolower($key)) ?? ''; + + foreach (self::SENSITIVE_KEYS as $sensitive) { + if ($normalized === str_replace('_', '', $sensitive)) { + return true; + } + } + + return false; + } +} diff --git a/config/addons.php b/config/addons.php index 0b725cebb..b43f1ea63 100644 --- a/config/addons.php +++ b/config/addons.php @@ -9,6 +9,9 @@ 'fulfillment' => [ 'enabled' => env('ADDONS_FULFILLMENT_ENABLED', false), + // A processing execution older than this is reclaimed by the scheduler. + 'processing_timeout_minutes' => (int) env('ADDONS_FULFILLMENT_PROCESSING_TIMEOUT', 15), + /* * The AddonTest service module is only registered in local/testing * environments, and only when this switch is on. It has no manifest diff --git a/database/migrations/2026_11_30_000005_add_claim_token_to_service_addon_executions.php b/database/migrations/2026_11_30_000005_add_claim_token_to_service_addon_executions.php new file mode 100644 index 000000000..407c44a1b --- /dev/null +++ b/database/migrations/2026_11_30_000005_add_claim_token_to_service_addon_executions.php @@ -0,0 +1,24 @@ +string('claim_token', 64)->nullable()->after('idempotency_key'); + $table->index('claim_token'); + }); + } + + public function down(): void + { + Schema::table('service_addon_executions', function (Blueprint $table) { + $table->dropIndex(['claim_token']); + $table->dropColumn('claim_token'); + }); + } +}; diff --git a/docs/developer/addon-executor.md b/docs/developer/addon-executor.md index 1c45da681..db7c3886c 100644 --- a/docs/developer/addon-executor.md +++ b/docs/developer/addon-executor.md @@ -27,6 +27,7 @@ admin screens and real server modules are deliberately not part of Stage 1. ```php 'fulfillment' => [ 'enabled' => env('ADDONS_FULFILLMENT_ENABLED', false), + 'processing_timeout_minutes' => env('ADDONS_FULFILLMENT_PROCESSING_TIMEOUT', 15), 'test_module_enabled' => env('ADDONS_TEST_MODULE_ENABLED', false), ], ``` @@ -65,6 +66,7 @@ One row per idempotent instruction. Important fields: - `status`: `pending`, `processing`, `completed`, `failed`, `retry`, `cancelled`, `manual_required`, `unsupported`, - `idempotency_key` (unique), +- `claim_token` — protects writes from a worker whose lease was reclaimed, - snapshot fields (`module`, `operation`, `parameter`, `value`, `unit`), - `request_payload`, `response_payload`, `result_message`, - `attempts`, `max_attempts`, `available_at`, timestamps. @@ -124,6 +126,17 @@ class MyModule implements ServerModuleInterface, ServiceAddonModuleInterface parameter, value, unit, options and configuration hash. A remove instruction also carries `appliedExecutionId`. +### Secrets + +Secrets must not be stored in `ProductAddon.options` or `ServiceAddon` snapshots. +The executor recursively rejects these keys, including nested JSON: + +`password`, `token`, `secret`, `api_key`, `authorization`, `access_key`, +`private_key`, `credentials`, `client_secret`. + +Request payloads, response payloads, result messages and exception logs are +sanitized before storage or logging. Raw exception traces are never stored. + The executor validates the operation and parameter against `addonCapabilities()` before calling the module. @@ -148,6 +161,45 @@ pending/retry -> processing Only one worker can claim a row. Module calls are not wrapped in a database transaction; only the claim and result writes are transactional. +### Claims, leases and stale processing + +The claim also writes a random `claim_token`. Every result write must match +that token and `status = processing`; a worker whose lease was taken over +cannot change the execution or its current attempt history. + +A `processing` execution older than +`ADDONS_FULFILLMENT_PROCESSING_TIMEOUT` minutes (default 15) is reclaimed by +the scheduler command: + +```text +processing -> retry +``` + +The reclaim clears the token, sets `available_at`, marks the abandoned attempt +as cancelled, and keeps the same execution and idempotency key. The module is +called again with the same `executionId`, so it must return the previous result +instead of applying a second effect. + +### Enqueue behaviour + +`enqueueApply()` reuses the existing execution for the same idempotency key: + +| Existing status | Behaviour | +|---|---| +| `completed` | returned, no dispatch | +| `processing` | returned, no dispatch | +| `pending` | returned, dispatched | +| `retry` | dispatched only when `available_at` is due | +| `failed` | returned, no automatic revival; use `retry()` | +| `cancelled` / `unsupported` / `manual_required` | returned, no dispatch | + +### Retry + +Retry is managed by `status` and `available_at` in the database and by +`pnlcs:addon-executions:process`, not by Laravel Queue retries alone. The job's +`tries` and `backoff` protect transport failures; module failures use the +stored execution status. The backoff is exponential: 5, 10, 20, 40 minutes. + ## Queue `ExecuteServiceAddonJob` runs after the execution is committed. The scheduler @@ -168,12 +220,18 @@ discoverable by manifest. It simulates effects in `service.module_data['addon_test']` and supports: - `simulate=fail_once` — transient failure, then success, +- `simulate=fail_attempts` — configurable number of transient failures, - `simulate=fail_permanent` — permanent failure, +- `simulate=manual_required` — safe manual-review result, - `simulate=refuse_remove` — safe removal refusal, +- `simulate=throw_exception` — sanitized exception/log path, +- `simulate=secret_response` — redaction of response payloads, - normal `increment`, `set`, `decrement`, `attach`, `detach`. It never calls a remote server. It is safe only for local/testing and is -guarded by both the environment and `ADDONS_TEST_MODULE_ENABLED`. +guarded by both the environment and `ADDONS_TEST_MODULE_ENABLED`. Outside that +guard it throws `AddonModuleUnavailableException`, which the executor records +as `unsupported` rather than retrying. ## Example executor use @@ -190,6 +248,8 @@ $executor->execute($removal); `enqueueApply()` and `enqueueRemoval()` return `null` when fulfilment is disabled, the add-on has no snapshot, or a removal has no completed apply. +When the feature flag is off, existing pending/retry rows are left untouched +and no job is dispatched; turning it back on lets the scheduler resume them. ## Not included in Stage 1 diff --git a/lang/de/addons.php b/lang/de/addons.php index c37d6c092..8e0cc4f8c 100644 --- a/lang/de/addons.php +++ b/lang/de/addons.php @@ -18,5 +18,8 @@ 'invalid_value' => 'Der Add-on-Wert ist für diese Operation ungültig.', 'value_below_minimum' => 'Der Add-on-Wert liegt unter dem Modulminimum.', 'value_above_maximum' => 'Der Add-on-Wert liegt über dem Modulmaximum.', + 'secret_not_allowed' => 'Die Add-on-Konfiguration enthält einen geheimen Wert und kann nicht gespeichert werden.', + 'lease_expired' => 'Die Ausführungslease ist abgelaufen; der Auftrag wurde erneut eingereiht.', + 'claim_superseded' => 'Dieser Versuch wurde durch eine neuere Auftragsübernahme ersetzt.', ], ]; diff --git a/lang/en/addons.php b/lang/en/addons.php index c237627ae..4e8c1ccf0 100644 --- a/lang/en/addons.php +++ b/lang/en/addons.php @@ -18,5 +18,8 @@ 'invalid_value' => 'The add-on value is not valid for this operation.', 'value_below_minimum' => 'The add-on value is below the module minimum.', 'value_above_maximum' => 'The add-on value is above the module maximum.', + 'secret_not_allowed' => 'Add-on configuration contains a secret value and cannot be stored.', + 'lease_expired' => 'Processing lease expired; the execution was queued for another attempt.', + 'claim_superseded' => 'This attempt was superseded by a newer execution claim.', ], ]; diff --git a/lang/pl/addons.php b/lang/pl/addons.php index 7ee51c38b..f1782dd77 100644 --- a/lang/pl/addons.php +++ b/lang/pl/addons.php @@ -18,5 +18,8 @@ 'invalid_value' => 'Wartość dodatku jest nieprawidłowa dla tej operacji.', 'value_below_minimum' => 'Wartość dodatku jest poniżej minimum modułu.', 'value_above_maximum' => 'Wartość dodatku jest powyżej maksimum modułu.', + 'secret_not_allowed' => 'Konfiguracja dodatku zawiera sekret i nie może zostać zapisana.', + 'lease_expired' => 'Lease realizacji wygasł; zlecenie wróciło do kolejki.', + 'claim_superseded' => 'Ta próba została zastąpiona przez nowsze przejęcie zlecenia.', ], ]; diff --git a/lang/tr/addons.php b/lang/tr/addons.php index 88fdce0e0..4920ad584 100644 --- a/lang/tr/addons.php +++ b/lang/tr/addons.php @@ -18,5 +18,8 @@ 'invalid_value' => 'Eklenti değeri bu işlem için geçersiz.', 'value_below_minimum' => 'Eklenti değeri modül minimumunun altında.', 'value_above_maximum' => 'Eklenti değeri modül maksimumunun üzerinde.', + 'secret_not_allowed' => 'Eklenti yapılandırması gizli bir değer içeriyor ve kaydedilemez.', + 'lease_expired' => 'Yürütme kirasi doldu; görev yeniden kuyruğa alındı.', + 'claim_superseded' => 'Bu deneme daha yeni bir görev sahiplenmesiyle değiştirildi.', ], ]; diff --git a/lang/zh/addons.php b/lang/zh/addons.php index 671d82f22..466282a08 100644 --- a/lang/zh/addons.php +++ b/lang/zh/addons.php @@ -18,5 +18,8 @@ 'invalid_value' => '此操作中的附加项值无效。', 'value_below_minimum' => '附加项值低于模块最小值。', 'value_above_maximum' => '附加项值高于模块最大值。', + 'secret_not_allowed' => '附加项配置包含机密值,无法保存。', + 'lease_expired' => '执行租约已过期;任务已重新排队。', + 'claim_superseded' => '此尝试已被更新的任务认领取代。', ], ]; diff --git a/modules/Servers/AddonTest/AddonTestModule.php b/modules/Servers/AddonTest/AddonTestModule.php index 4ead1d6bd..f9c5b0583 100644 --- a/modules/Servers/AddonTest/AddonTestModule.php +++ b/modules/Servers/AddonTest/AddonTestModule.php @@ -4,6 +4,7 @@ use App\Contracts\ServerModuleInterface; use App\Contracts\ServiceAddonModuleInterface; +use App\Exceptions\AddonModuleUnavailableException; use App\Models\Server; use App\Models\Service; use App\Support\Addons\AddonInstruction; @@ -78,6 +79,27 @@ public function applyAddon(Service $service, AddonInstruction $instruction): arr } } + if ($simulate === 'fail_attempts') { + $key = 'addon_test:fail_attempts:'.$instruction->executionId; + $attempt = (int) Cache::get($key, 0) + 1; + Cache::put($key, $attempt, 3600); + + if ($attempt <= (int) ($instruction->options['fail_attempts'] ?? 1)) { + return $this->result(false, 'Simulated transient failure '.$attempt, ['retryable' => true]); + } + } + + if ($simulate === 'throw_exception') { + throw new RuntimeException('token=super-secret-token'); + } + + if ($simulate === 'secret_response') { + return $this->result(true, 'Completed with token=super-secret-token', [ + 'token' => 'super-secret-token', + 'nested' => ['password' => 'nested-secret'], + ]); + } + if ($simulate === 'manual_required') { return $this->result(false, 'Simulated manual review required', ['manual_required' => true]); } @@ -210,7 +232,7 @@ private function assertAvailable(): void { if (! app()->environment(['local', 'testing']) || ! config('addons.fulfillment.test_module_enabled', false)) { - throw new RuntimeException('The AddonTest module is only available in local/testing.'); + throw new AddonModuleUnavailableException('The AddonTest module is only available in local/testing.'); } } diff --git a/tests/Feature/AddonExecutorTest.php b/tests/Feature/AddonExecutorTest.php index 32fc03080..d5e92e3c1 100644 --- a/tests/Feature/AddonExecutorTest.php +++ b/tests/Feature/AddonExecutorTest.php @@ -2,6 +2,8 @@ use App\Enums\AddonExecutionAction; use App\Enums\AddonExecutionStatus; +use App\Exceptions\AddonModuleUnavailableException; +use App\Jobs\ExecuteServiceAddonJob; use App\Models\Client; use App\Models\Product; use App\Models\ProductAddon; @@ -11,6 +13,8 @@ use App\Models\ServiceAddonExecutionAttempt; use App\Services\Addons\AddonExecutionService; use App\Services\Module\ModuleRegistry; +use App\Support\Addons\AddonInstruction; +use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Queue; use Modules\Servers\AddonTest\AddonTestModule; @@ -75,6 +79,7 @@ function addonTestServiceAddon( expect(app(AddonExecutionService::class)->enqueueApply($addon))->toBeNull() ->and(ServiceAddonExecution::count())->toBe(0); + Queue::assertNothingPushed(); }); it('applies an addon through the test module and records the attempt', function () { @@ -297,9 +302,242 @@ function addonTestServiceAddon( config()->set('addons.fulfillment.test_module_enabled', false); expect(fn () => (new AddonTestModule)->addonCapabilities()) - ->toThrow(RuntimeException::class); + ->toThrow(AddonModuleUnavailableException::class); }); +it('marks an unavailable test module as unsupported instead of retrying', function () { + config()->set('addons.fulfillment.test_module_enabled', false); + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + expect($execution->fresh()->status)->toBe(AddonExecutionStatus::Unsupported) + ->and($execution->fresh()->attempts)->toBe(1); +}); + +it('rejects a configuration containing a secret before creating an execution', function () { + $service = addonTestService(); + $productAddon = addonTestProductAddon(['options' => ['nested' => ['password' => 'very-secret']]]); + $addon = addonTestServiceAddon($service, $productAddon); + + expect(fn () => app(AddonExecutionService::class)->enqueueApply($addon)) + ->toThrow(InvalidArgumentException::class); + + expect(ServiceAddonExecution::count())->toBe(0); +}); + +it('redacts secrets from response payloads and messages', function () { + $service = addonTestService(); + $productAddon = addonTestProductAddon(['options' => ['simulate' => 'secret_response']]); + $addon = addonTestServiceAddon($service, $productAddon); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + $execution->refresh(); + + expect($execution->status)->toBe(AddonExecutionStatus::Completed) + ->and($execution->response_payload['token'])->toBe('[redacted]') + ->and($execution->response_payload['nested']['password'])->toBe('[redacted]') + ->and($execution->result_message)->not->toContain('super-secret-token'); +}); + +it('keeps previous attempts and records retry results separately', function () { + $service = addonTestService(); + $productAddon = addonTestProductAddon(['options' => ['simulate' => 'fail_once']]); + $addon = addonTestServiceAddon($service, $productAddon); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + $executor->retry($execution->fresh()); + + $attempts = ServiceAddonExecutionAttempt::where('execution_id', $execution->id)->orderBy('attempt_no')->get(); + + expect($attempts)->toHaveCount(2) + ->and($attempts[0]->attempt_no)->toBe(1) + ->and($attempts[0]->status)->toBe(AddonExecutionStatus::Retry) + ->and($attempts[0]->error)->not->toBeNull() + ->and($attempts[1]->attempt_no)->toBe(2) + ->and($attempts[1]->status)->toBe(AddonExecutionStatus::Completed) + ->and($attempts[1]->error)->toBeNull() + ->and($attempts[0]->request_payload)->not->toBeNull() + ->and($attempts[1]->request_payload)->not->toBeNull(); +}); + +it('uses 5, 10 and 20 minute backoff for transient failures', function () { + $service = addonTestService(); + $productAddon = addonTestProductAddon([ + 'options' => ['simulate' => 'fail_attempts', 'fail_attempts' => 3], + ]); + $addon = addonTestServiceAddon($service, $productAddon); + $executor = app(AddonExecutionService::class); + $execution = $executor->enqueueApply($addon); + + foreach ([5, 10, 20] as $minutes) { + $executor->execute($execution->fresh()); + $available = $execution->fresh()->available_at; + + expect(abs(now()->diffInMinutes($available)) >= $minutes - 1)->toBeTrue() + ->and(abs(now()->diffInMinutes($available)) <= $minutes + 1)->toBeTrue(); + + $execution->fresh()->update([ + 'status' => AddonExecutionStatus::Retry, + 'available_at' => now(), + ]); + } + + $executor->execute($execution->fresh()); + + expect($execution->fresh()->status)->toBe(AddonExecutionStatus::Completed); +}); + +it('can retry a failed execution without creating another execution', function () { + $service = addonTestService(); + $productAddon = addonTestProductAddon(['options' => ['simulate' => 'fail_once']]); + $addon = addonTestServiceAddon($service, $productAddon); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + $execution->update(['status' => AddonExecutionStatus::Failed]); + + expect($executor->retry($execution->fresh()))->toBeTrue() + ->and(ServiceAddonExecution::count())->toBe(1) + ->and($execution->fresh()->status)->toBe(AddonExecutionStatus::Completed); +}); + +it('reclaims stale processing and replays it idempotently', function () { + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + $execution = $executor->enqueueApply($addon); + + $execution->update([ + 'status' => AddonExecutionStatus::Processing, + 'claim_token' => 'old-claim-token', + 'started_at' => now()->subMinutes(20), + 'attempts' => 1, + ]); + + $oldAttempt = ServiceAddonExecutionAttempt::create([ + 'execution_id' => $execution->id, + 'attempt_no' => 1, + 'status' => AddonExecutionStatus::Processing, + 'request_payload' => $execution->request_payload, + 'started_at' => now()->subMinutes(20), + ]); + + $instruction = new AddonInstruction( + executionId: $execution->id, + serviceAddonId: $addon->id, + operation: 'increment', + parameter: 'storage_quota', + value: '50', + unit: 'GB', + options: [], + configurationHash: data_get($execution->request_payload, 'configuration_hash', ''), + ); + + app(AddonTestModule::class)->applyAddon($service, $instruction); + + $this->artisan('pnlcs:addon-executions:process', ['--id' => $execution->id]) + ->assertSuccessful(); + + $execution->refresh(); + + expect($execution->status)->toBe(AddonExecutionStatus::Completed) + ->and($execution->attempts)->toBe(2) + ->and((float) $service->fresh()->module_data['addon_test']['state']['storage_quota'])->toBe(50.0) + ->and(ServiceAddonExecutionAttempt::where('execution_id', $execution->id)->count())->toBe(2) + ->and($oldAttempt->fresh()->status)->toBe(AddonExecutionStatus::Cancelled); +}); + +it('does not let an old worker overwrite a newer result', function () { + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + $execution->refresh(); + + $finish = new ReflectionMethod($executor, 'finish'); + $finish->setAccessible(true); + + $written = $finish->invoke( + $executor, + $execution, + AddonExecutionStatus::Failed, + null, + 'old worker result', + null, + null, + 'old-claim-token' + ); + + expect($written)->toBeFalse() + ->and($execution->fresh()->status)->toBe(AddonExecutionStatus::Completed) + ->and($execution->fresh()->attempts)->toBe(1); +}); + +it('does not execute completed from job or scheduler', function () { + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + (new ExecuteServiceAddonJob($execution->id))->handle($executor); + $this->artisan('pnlcs:addon-executions:process', ['--id' => $execution->id]) + ->assertSuccessful(); + + expect($execution->fresh()->attempts)->toBe(1) + ->and($executor->retry($execution->fresh()))->toBeFalse(); +}); + +it('keeps execution and attempt history when the addon or service is removed', function () { + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + $addon->delete(); + + expect($execution->fresh()->service_addon_id)->toBeNull() + ->and(ServiceAddonExecutionAttempt::where('execution_id', $execution->id)->exists())->toBeTrue(); + + $service->delete(); + + expect($execution->fresh()->service_id)->toBeNull() + ->and(ServiceAddonExecutionAttempt::where('execution_id', $execution->id)->exists())->toBeTrue(); + + $execution->delete(); + + expect(ServiceAddonExecutionAttempt::where('execution_id', $execution->id)->exists())->toBeFalse(); +}); + +it('keeps pending executions while the feature flag is off and resumes them', function () { + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + $execution = $executor->enqueueApply($addon); + + config()->set('addons.fulfillment.enabled', false); + expect($executor->execute($execution))->toBeFalse() + ->and($execution->fresh()->status)->toBe(AddonExecutionStatus::Pending) + ->and($addon->fresh()->fulfillment_status)->toBe(AddonExecutionStatus::NotConfigured); + + config()->set('addons.fulfillment.enabled', true); + $this->artisan('pnlcs:addon-executions:process', ['--id' => $execution->id]) + ->assertSuccessful(); + + expect($execution->fresh()->status)->toBe(AddonExecutionStatus::Completed); +}); it('removes using the applied configuration snapshot, not a later edit', function () { $service = addonTestService(); @@ -327,3 +565,50 @@ function addonTestServiceAddon( ->and(data_get($remove->fresh()->request_payload, 'configuration.value'))->toBe('50') ->and($service->fresh()->module_data['addon_test']['state'])->not->toHaveKey('storage_quota'); }); + +it('redacts secrets from exception logs', function () { + Log::spy(); + $service = addonTestService(); + $productAddon = addonTestProductAddon(['options' => ['simulate' => 'throw_exception']]); + $addon = addonTestServiceAddon($service, $productAddon); + $executor = app(AddonExecutionService::class); + + $execution = $executor->enqueueApply($addon); + $executor->execute($execution); + + expect($execution->fresh()->status)->toBe(AddonExecutionStatus::Retry) + ->and($execution->fresh()->result_message)->not->toContain('super-secret-token'); + + Log::shouldHaveReceived('error')->once()->withArgs( + fn (string $message, array $context): bool => ! str_contains(json_encode($context), 'super-secret-token') + ); +}); + +it('allows only one of two workers to claim the same pending execution', function () { + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + $execution = $executor->enqueueApply($addon); + + $first = app(AddonExecutionService::class)->execute($execution->fresh()); + $second = app(AddonExecutionService::class)->execute($execution->fresh()); + + expect([$first, $second])->toContain(true) + ->and([$first, $second])->toContain(false) + ->and($execution->fresh()->attempts)->toBe(1) + ->and(ServiceAddonExecutionAttempt::where('execution_id', $execution->id)->count())->toBe(1); +}); + +it('does not auto-resume a failed execution from enqueueApply', function () { + $service = addonTestService(); + $addon = addonTestServiceAddon($service); + $executor = app(AddonExecutionService::class); + $execution = $executor->enqueueApply($addon); + $execution->update(['status' => AddonExecutionStatus::Failed]); + + $again = $executor->enqueueApply($addon); + + expect($again->id)->toBe($execution->id) + ->and($again->status)->toBe(AddonExecutionStatus::Failed); + Queue::assertNothingPushed(); +}); diff --git a/tests/Feature/ScheduledCommandsTest.php b/tests/Feature/ScheduledCommandsTest.php index 0f89023ec..80a3566da 100644 --- a/tests/Feature/ScheduledCommandsTest.php +++ b/tests/Feature/ScheduledCommandsTest.php @@ -79,7 +79,7 @@ function cronFixtures(): void $commands = []; foreach (Schedule::events() as $event) { - if (preg_match('/artisan[\'"]? (pnlcs:[a-z\-]+)/', $event->command ?? '', $m)) { + if (preg_match('/artisan[\'"]? (pnlcs:[a-z\-:]+)/', $event->command ?? '', $m)) { $commands[] = $m[1]; } }