TenantAtlas/apps/platform/app/Services/Providers/ProviderOperationStartGate.php
Ahmed Darrazi 19132dc433
Some checks failed
PR Fast Feedback / fast-feedback (pull_request) Failing after 1m28s
feat: normalize provider connection scope contracts
2026-05-07 21:27:15 +02:00

386 lines
16 KiB
PHP

<?php
namespace App\Services\Providers;
use App\Models\OperationRun;
use App\Models\ProviderConnection;
use App\Models\ManagedEnvironment;
use App\Models\User;
use App\Services\OperationRunService;
use App\Support\Auth\Capabilities;
use App\Support\Operations\ExecutionAuthorityMode;
use App\Support\Operations\OperationRunCapabilityResolver;
use App\Support\Providers\ProviderNextStepsRegistry;
use App\Support\Providers\ProviderReasonCodes;
use App\Support\Providers\TargetScope\ProviderConnectionTargetScopeDescriptor;
use App\Support\Providers\TargetScope\ProviderConnectionTargetScopeNormalizer;
use App\Support\Providers\TargetScope\ProviderIdentityContextMetadata;
use App\Support\Verification\BlockedVerificationReportFactory;
use App\Support\Verification\StaleQueuedVerificationReportFactory;
use App\Support\Verification\VerificationReportWriter;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
use ReflectionFunction;
use ReflectionMethod;
final class ProviderOperationStartGate
{
public function __construct(
private readonly OperationRunService $runs,
private readonly ProviderOperationRegistry $registry,
private readonly ProviderConnectionResolver $resolver,
private readonly ProviderNextStepsRegistry $nextStepsRegistry,
private readonly OperationRunCapabilityResolver $capabilityResolver,
private readonly ProviderConnectionTargetScopeNormalizer $targetScopeNormalizer,
) {}
/**
* @param array<string, mixed> $extraContext
*/
public function start(
ManagedEnvironment $tenant,
?ProviderConnection $connection,
string $operationType,
callable $dispatcher,
?User $initiator = null,
array $extraContext = [],
): ProviderOperationStartResult {
$definition = $this->registry->get($operationType);
$binding = $this->resolveProviderBinding($operationType, $connection);
if (($binding['binding_status'] ?? null) !== ProviderOperationRegistry::BINDING_ACTIVE) {
return $this->startBlocked(
tenant: $tenant,
operationType: $operationType,
provider: (string) ($binding['provider'] ?? 'unknown'),
module: (string) $definition['module'],
reasonCode: ProviderReasonCodes::ProviderBindingUnsupported,
extensionReasonCode: 'ext.provider_binding_missing',
reasonMessage: 'No explicit provider binding supports this operation/provider combination.',
connection: $connection,
initiator: $initiator,
extraContext: array_merge($extraContext, [
'provider_binding' => $this->bindingContext($binding),
]),
);
}
$resolution = $connection instanceof ProviderConnection
? $this->resolver->validateConnection($tenant, (string) $binding['provider'], $connection)
: $this->resolver->resolveDefault($tenant, (string) $binding['provider']);
if (! $resolution->resolved || ! $resolution->connection instanceof ProviderConnection) {
return $this->startBlocked(
tenant: $tenant,
operationType: $operationType,
provider: (string) $binding['provider'],
module: (string) $definition['module'],
reasonCode: $resolution->effectiveReasonCode(),
extensionReasonCode: $resolution->extensionReasonCode,
reasonMessage: $resolution->message,
connection: $resolution->connection ?? $connection,
initiator: $initiator,
extraContext: array_merge($extraContext, [
'provider_binding' => $this->bindingContext($binding),
]),
);
}
return DB::transaction(function () use ($tenant, $operationType, $dispatcher, $initiator, $extraContext, $definition, $binding, $resolution): ProviderOperationStartResult {
$connection = $resolution->connection;
if (! $connection instanceof ProviderConnection) {
throw new InvalidArgumentException('Resolved provider connection is missing.');
}
$lockedConnection = ProviderConnection::query()
->whereKey($connection->getKey())
->lockForUpdate()
->firstOrFail();
$activeRun = OperationRun::query()
->where('managed_environment_id', $tenant->getKey())
->active()
->where('context->provider_connection_id', (int) $lockedConnection->getKey())
->orderByDesc('id')
->lockForUpdate()
->first();
if ($activeRun instanceof OperationRun) {
if ($this->runs->isStaleQueuedRun($activeRun)) {
$this->runs->failStaleQueuedRun($activeRun);
if ($activeRun->type === 'provider.connection.check') {
VerificationReportWriter::write(
run: $activeRun,
checks: StaleQueuedVerificationReportFactory::checks($activeRun),
identity: StaleQueuedVerificationReportFactory::identity($activeRun),
);
$activeRun->refresh();
}
$activeRun = null;
}
}
if ($activeRun instanceof OperationRun) {
if ($activeRun->type === $operationType) {
return ProviderOperationStartResult::deduped($activeRun);
}
return ProviderOperationStartResult::scopeBusy($activeRun);
}
$context = array_merge($extraContext, [
'execution_authority_mode' => is_string($extraContext['execution_authority_mode'] ?? null)
? $extraContext['execution_authority_mode']
: ($initiator instanceof User ? ExecutionAuthorityMode::ActorBound->value : ExecutionAuthorityMode::SystemAuthority->value),
'required_capability' => $this->resolveRequiredCapability($operationType, $extraContext),
'provider' => $lockedConnection->provider,
'module' => $definition['module'],
'provider_binding' => $this->bindingContext($binding),
'provider_connection_id' => (int) $lockedConnection->getKey(),
'connection_type' => $lockedConnection->connection_type?->value ?? $lockedConnection->connection_type,
'target_scope' => $this->targetScopeContextForConnection($lockedConnection),
'provider_context' => $this->providerContextForConnection($lockedConnection),
]);
$run = $this->runs->ensureRunWithIdentity(
tenant: $tenant,
type: $operationType,
identityInputs: [
'provider_connection_id' => (int) $lockedConnection->getKey(),
],
context: $context,
initiator: $initiator,
);
$dispatched = false;
if ($run->wasRecentlyCreated) {
$this->invokeDispatcher($dispatcher, $run);
$dispatched = true;
}
return ProviderOperationStartResult::started($run, $dispatched);
});
}
/**
* @param array<string, mixed> $extraContext
*/
private function startBlocked(
ManagedEnvironment $tenant,
string $operationType,
string $provider,
string $module,
string $reasonCode,
?string $extensionReasonCode = null,
?string $reasonMessage = null,
?ProviderConnection $connection = null,
?User $initiator = null,
array $extraContext = [],
): ProviderOperationStartResult {
$context = array_merge($extraContext, [
'execution_authority_mode' => is_string($extraContext['execution_authority_mode'] ?? null)
? $extraContext['execution_authority_mode']
: ($initiator instanceof User ? ExecutionAuthorityMode::ActorBound->value : ExecutionAuthorityMode::SystemAuthority->value),
'required_capability' => $this->resolveRequiredCapability($operationType, $extraContext),
'provider' => $provider,
'module' => $module,
'target_scope' => $connection instanceof ProviderConnection
? $this->targetScopeContextForConnection($connection)
: $this->targetScopeContextForTenant($tenant, $provider),
]);
$identityInputs = [
'provider' => $provider,
'reason_code' => $reasonCode,
];
if (is_string($extensionReasonCode) && $extensionReasonCode !== '') {
$context['reason_code_extension'] = $extensionReasonCode;
$identityInputs['reason_code_extension'] = $extensionReasonCode;
}
if ($connection instanceof ProviderConnection) {
$context['provider_connection_id'] = (int) $connection->getKey();
$context['connection_type'] = $connection->connection_type?->value ?? $connection->connection_type;
$context['provider_context'] = $this->providerContextForConnection($connection);
$identityInputs['provider_connection_id'] = (int) $connection->getKey();
}
$run = $this->runs->ensureRunWithIdentity(
tenant: $tenant,
type: $operationType,
identityInputs: $identityInputs,
context: $context,
initiator: $initiator,
);
$run = $this->runs->finalizeBlockedRun(
$run,
reasonCode: ProviderReasonCodes::isKnown($reasonCode) ? $reasonCode : ProviderReasonCodes::UnknownError,
nextSteps: $this->nextStepsRegistry->forReason($tenant, $reasonCode, $connection),
message: $reasonMessage,
);
if ($operationType === 'provider.connection.check') {
VerificationReportWriter::write(
run: $run,
checks: BlockedVerificationReportFactory::checks($run),
identity: BlockedVerificationReportFactory::identity($run),
);
$run->refresh();
}
return ProviderOperationStartResult::blocked($run);
}
private function invokeDispatcher(callable $dispatcher, OperationRun $run): void
{
$ref = null;
if (is_array($dispatcher) && count($dispatcher) === 2) {
$ref = new ReflectionMethod($dispatcher[0], (string) $dispatcher[1]);
} elseif (is_string($dispatcher) && str_contains($dispatcher, '::')) {
[$class, $method] = explode('::', $dispatcher, 2);
$ref = new ReflectionMethod($class, $method);
} elseif ($dispatcher instanceof \Closure) {
$ref = new ReflectionFunction($dispatcher);
} elseif (is_object($dispatcher) && method_exists($dispatcher, '__invoke')) {
$ref = new ReflectionMethod($dispatcher, '__invoke');
}
if ($ref && $ref->getNumberOfParameters() >= 1) {
$dispatcher($run);
return;
}
$dispatcher();
}
/**
* @return array{operation_type: string, provider: string, binding_status: string, handler_notes: string, exception_notes: string}
*/
private function resolveProviderBinding(string $operationType, ?ProviderConnection $connection): array
{
if ($connection instanceof ProviderConnection) {
$provider = trim((string) $connection->provider);
return $this->registry->bindingFor($operationType, $provider)
?? $this->registry->unsupportedBinding($operationType, $provider);
}
return $this->registry->activeBindingFor($operationType)
?? $this->registry->unsupportedBinding($operationType, 'unknown');
}
/**
* @param array{operation_type: string, provider: string, binding_status: string, handler_notes: string, exception_notes: string} $binding
* @return array{provider: string, binding_status: string, handler_notes: string, exception_notes: string}
*/
private function bindingContext(array $binding): array
{
return [
'provider' => (string) $binding['provider'],
'binding_status' => (string) $binding['binding_status'],
'handler_notes' => (string) $binding['handler_notes'],
'exception_notes' => (string) $binding['exception_notes'],
];
}
/**
* @return array{
* provider: string,
* scope_kind: string,
* scope_identifier: string,
* scope_display_name: string,
* shared_label: string,
* shared_help_text: string
* }
*/
private function targetScopeContextForConnection(ProviderConnection $connection): array
{
try {
return $this->targetScopeNormalizer->descriptorForConnection($connection)->toArray();
} catch (InvalidArgumentException) {
$identifier = trim((string) $connection->entra_tenant_id);
$fallbackIdentifier = $connection->tenant instanceof ManagedEnvironment
? trim((string) $connection->tenant->graphTenantId())
: '';
return ProviderConnectionTargetScopeDescriptor::fromInput(
provider: (string) $connection->provider,
scopeKind: ProviderConnectionTargetScopeDescriptor::SCOPE_KIND_TENANT,
scopeIdentifier: $identifier !== '' ? $identifier : ($fallbackIdentifier !== '' ? $fallbackIdentifier : (string) $connection->getKey()),
scopeDisplayName: (string) ($connection->tenant?->name ?? $connection->display_name ?? $identifier),
)->toArray();
}
}
/**
* @return array{
* provider: string,
* scope_kind: string,
* scope_identifier: string,
* scope_display_name: string,
* shared_label: string,
* shared_help_text: string
* }
*/
private function targetScopeContextForTenant(ManagedEnvironment $tenant, string $provider): array
{
$identifier = trim($tenant->providerTenantContext());
return ProviderConnectionTargetScopeDescriptor::fromInput(
provider: $provider !== '' ? $provider : 'unknown',
scopeKind: ProviderConnectionTargetScopeDescriptor::SCOPE_KIND_TENANT,
scopeIdentifier: $identifier,
scopeDisplayName: (string) ($tenant->name ?? $identifier),
)->toArray();
}
/**
* @return array{provider: string, details: list<array<string, string>>}
*/
private function providerContextForConnection(ProviderConnection $connection): array
{
return [
'provider' => (string) $connection->provider,
'details' => array_map(
static fn (ProviderIdentityContextMetadata $detail): array => $detail->toArray(),
$this->targetScopeNormalizer->contextualIdentityDetailsForConnection($connection),
),
];
}
/**
* @param array<string, mixed> $extraContext
*/
private function resolveRequiredCapability(string $operationType, array $extraContext): ?string
{
if (is_string($extraContext['required_capability'] ?? null) && trim((string) $extraContext['required_capability']) !== '') {
return trim((string) $extraContext['required_capability']);
}
if ($this->registry->isAllowed($operationType)) {
$definition = $this->registry->get($operationType);
$requiredCapability = $definition['required_capability'] ?? null;
if (is_string($requiredCapability) && trim($requiredCapability) !== '') {
return trim($requiredCapability);
}
}
if ($this->registry->isAllowed($operationType)) {
return Capabilities::PROVIDER_RUN;
}
return $this->capabilityResolver->requiredExecutionCapabilityForType($operationType);
}
}