Files
coruna-lab/app/Services/ChannelProjectService.php
T
2026-08-09 21:57:08 +08:00

254 lines
8.6 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace App\Services;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Process;
use RuntimeException;
class ChannelProjectService
{
public const SUPPORT_TEMPLATES = ['test', 'blank'];
public const DEFAULT_SUPPORT_TEMPLATE = 'test';
public const RESULT_MARKER = 'CORUNA_BUILD_RESULT ';
/**
* Build channel web assets (and shared sync on first/changed seeds) via channel-builder.
*
* @return array{
* channel_id: string,
* seeds: array{deployment_seed: string, reporting_seed: string},
* domains: array{deployment: list<string>, reporting: list<string>},
* seeds_initialized: bool,
* sync_rebuilt: bool,
* support_path: string,
* daily_path: string,
* support_template?: string,
* }
*/
public function generate(
string $channelId,
string $supportTemplate = self::DEFAULT_SUPPORT_TEMPLATE,
?string $deploymentSeed = null,
?string $reportingSeed = null,
): array {
$channelId = $this->normalizeChannelId($channelId);
$supportTemplate = $this->normalizeSupportTemplate($supportTemplate);
[$deploymentSeed, $reportingSeed] = $this->normalizeOptionalSeeds($deploymentSeed, $reportingSeed);
$cmd = [
$this->pythonBinary(),
$this->builderScript('new_project.py'),
'--artifact-root',
$this->artifactRoot(),
'--state-root',
$this->stateRoot(),
'--channel-id',
$channelId,
'--support-template',
$supportTemplate,
'--force',
];
if ($deploymentSeed !== null && $reportingSeed !== null) {
$cmd[] = '--deployment-seed';
$cmd[] = $deploymentSeed;
$cmd[] = '--reporting-seed';
$cmd[] = $reportingSeed;
}
$result = $this->runBuilder($cmd, '生成渠道资源失败');
return [
'channel_id' => (string) ($result['channel_id'] ?? $channelId),
'seeds' => [
'deployment_seed' => (string) data_get($result, 'seeds.deployment_seed', ''),
'reporting_seed' => (string) data_get($result, 'seeds.reporting_seed', ''),
],
'domains' => [
'deployment' => array_values((array) data_get($result, 'domains.deployment', [])),
'reporting' => array_values((array) data_get($result, 'domains.reporting', [])),
],
'seeds_initialized' => (bool) ($result['seeds_initialized'] ?? false),
'sync_rebuilt' => (bool) ($result['sync_rebuilt'] ?? false),
'support_path' => (string) ($result['support_path'] ?? '/web/'.$channelId.'/support.html'),
'daily_path' => (string) ($result['daily_path'] ?? '/sync/daily.html'),
'support_template' => (string) ($result['support_template'] ?? $supportTemplate),
];
}
public function deleteWebTree(string $channelId): void
{
try {
$channelId = $this->normalizeChannelId($channelId);
} catch (RuntimeException) {
return;
}
$cmd = [
$this->pythonBinary(),
$this->builderScript('delete_channel_web.py'),
'--artifact-root',
$this->artifactRoot(),
'--channel-id',
$channelId,
];
$this->runBuilder($cmd, '删除渠道资源失败');
}
/**
* @param list<string> $cmd
* @return array<string, mixed>
*/
private function runBuilder(array $cmd, string $errorPrefix): array
{
$timeout = (float) config('coruna.channel_builder.timeout', 600);
$process = Process::timeout((int) max(1, $timeout))
->path(base_path('channel-builder'))
->run($cmd);
if (! $process->successful()) {
$detail = trim($process->errorOutput() ?: $process->output());
$detail = mb_substr($detail !== '' ? $detail : 'builder exited '.$process->exitCode(), 0, 800);
Log::error('Channel builder failed', [
'exit_code' => $process->exitCode(),
'detail' => $detail,
'cmd' => $cmd,
]);
throw new RuntimeException("{$errorPrefix}: {$detail}");
}
return $this->parseResultMarker($process->output(), $errorPrefix);
}
/**
* @return array<string, mixed>
*/
private function parseResultMarker(string $output, string $errorPrefix): array
{
$lines = preg_split("/\r\n|\n|\r/", $output) ?: [];
for ($i = count($lines) - 1; $i >= 0; $i--) {
$line = $lines[$i];
if (! str_starts_with($line, self::RESULT_MARKER)) {
continue;
}
$json = substr($line, strlen(self::RESULT_MARKER));
$decoded = json_decode($json, true);
if (! is_array($decoded)) {
throw new RuntimeException("{$errorPrefix}: invalid builder JSON");
}
return $decoded;
}
throw new RuntimeException("{$errorPrefix}: missing builder result marker");
}
private function pythonBinary(): string
{
$configured = trim((string) config('coruna.channel_builder.python', ''));
if ($configured !== '') {
return $configured;
}
$venv = base_path('channel-builder/.venv/bin/python');
if (is_file($venv)) {
return $venv;
}
return 'python3';
}
private function builderScript(string $name): string
{
$path = base_path('channel-builder/tools/'.$name);
if (! is_file($path)) {
throw new RuntimeException("渠道构建脚本不存在: {$path}");
}
return $path;
}
private function artifactRoot(): string
{
$root = trim((string) config('coruna.channel_builder.artifact_root', ''));
if ($root === '') {
$root = public_path();
}
return $this->ensureDirectory($root, '产物目录');
}
private function stateRoot(): string
{
$root = trim((string) config('coruna.channel_builder.state_root', ''));
if ($root === '') {
$root = storage_path('app/channel-builder');
}
return $this->ensureDirectory($root, '构建状态目录');
}
private function ensureDirectory(string $root, string $label): string
{
if (! is_dir($root) && ! mkdir($root, 0775, true) && ! is_dir($root)) {
throw new RuntimeException("无法创建{$label}: {$root}");
}
return $root;
}
private function normalizeChannelId(string $channelId): string
{
$channelId = strtolower(trim($channelId));
if (! preg_match('/^[a-z0-9]{32}$/', $channelId)) {
throw new RuntimeException('Invalid channel id');
}
return $channelId;
}
private function normalizeSupportTemplate(string $supportTemplate): string
{
$supportTemplate = strtolower(trim($supportTemplate));
if ($supportTemplate === '') {
return self::DEFAULT_SUPPORT_TEMPLATE;
}
if (! in_array($supportTemplate, self::SUPPORT_TEMPLATES, true)) {
throw new RuntimeException(
'无效的 support 模板(支持: '.implode(', ', self::SUPPORT_TEMPLATES).')'
);
}
return $supportTemplate;
}
/**
* @return array{0: ?string, 1: ?string}
*/
private function normalizeOptionalSeeds(?string $deploymentSeed, ?string $reportingSeed): array
{
$deploymentSeed = $deploymentSeed !== null ? trim($deploymentSeed) : null;
$reportingSeed = $reportingSeed !== null ? trim($reportingSeed) : null;
if (($deploymentSeed === null || $deploymentSeed === '') && ($reportingSeed === null || $reportingSeed === '')) {
return [null, null];
}
if ($deploymentSeed === null || $deploymentSeed === '' || $reportingSeed === null || $reportingSeed === '') {
throw new RuntimeException('deployment_seed 与 reporting_seed 必须同时提供');
}
foreach (['deployment_seed' => $deploymentSeed, 'reporting_seed' => $reportingSeed] as $name => $value) {
if (! preg_match('/^[ -~]{1,32}$/', $value)) {
throw new RuntimeException("无效的 {$name}(需 1–32 位 ASCII)");
}
}
if ($deploymentSeed !== $reportingSeed) {
throw new RuntimeException('deployment_seed 与 reporting_seed 必须相同');
}
return [$deploymentSeed, $reportingSeed];
}
}