Update LaySite from upstream release ZIP archives

This commit is contained in:
2026-11-27 16:55:37 +08:00
committed by enoch
parent a68f766f6e
commit 9e6679f493
3 changed files with 424 additions and 39 deletions
+417
View File
@@ -0,0 +1,417 @@
#!/usr/bin/env php
<?php
declare(strict_types=1);
final class LaySiteUpdater
{
private const HOST = 'https://git.laysense.com';
private const PROJECT = '/laysense/laysite';
private const LEGACY_BASES = ['1.3.0' => 'd5bedabaa1d0187e29060c41fb030e9587a8692f'];
private const MANAGED = '/^(?:(?:app|bin|config|public|resources|support|\.agents\/skills\/laysite-mcp)\/.+|\.env\.example|\.gitattributes|\.gitignore|LICENSE|NOTICE|README\.md|VERSION|composer\.(?:json|lock)|start\.php)$/D';
private const MAX_ARCHIVE_BYTES = 64 * 1024 * 1024;
private const MAX_EXPANDED_BYTES = 256 * 1024 * 1024;
public function __construct(private readonly string $root)
{
}
public function check(): void
{
$current = $this->version();
$latest = null;
$deadline = hrtime(true) + 10_000_000_000;
for ($page = 1; ; $page++) {
$timeout = (int) (($deadline - hrtime(true)) / 1_000_000);
if ($timeout <= 0) {
throw new RuntimeException('查询 LaySite 发布列表超时。');
}
$stream = fopen('php://temp', 'w+b');
try {
self::download('/api/v1/repos' . self::PROJECT . "/tags?limit=50&page=$page", $stream, 262144, $timeout);
rewind($stream);
$tags = json_decode(stream_get_contents($stream), flags: JSON_THROW_ON_ERROR);
} finally {
fclose($stream);
}
if (!is_array($tags)) {
throw new RuntimeException('LaySite 发布列表格式无效。');
}
foreach ($tags as $tag) {
$name = $tag->name ?? null;
if (!is_string($name)) {
throw new RuntimeException('LaySite 发布列表格式无效。');
}
if (preg_match('/^v(\d+\.\d+\.\d+)$/D', $name, $match)
&& ($latest === null || version_compare($match[1], $latest, '>'))) {
$latest = $match[1];
}
}
if (count($tags) < 50) {
break;
}
}
printf("当前版本 v%s\n%s\n", $current, $latest === null ? '上游暂无发布版本。' : '最新发布版本 v' . $latest);
}
public function update(string $target, string $backup): void
{
$runtime = $this->root . '/runtime';
self::makeDirectory($runtime);
$lock = fopen($runtime . '/release-update.lock', 'c');
if ($lock === false || !flock($lock, LOCK_EX | LOCK_NB)) {
throw new RuntimeException('无法取得 LaySite 更新锁。');
}
$pending = $runtime . '/release-update-pending';
$work = $this->root . '/.laysite-update-' . bin2hex(random_bytes(8));
try {
if (file_exists($pending) || is_link($pending)) {
throw new RuntimeException('上次更新尚未完成。请保留该次更新的备份,并检查 ' . trim((string) file_get_contents($pending)));
}
$current = $this->version();
$comparison = version_compare(substr($target, 1), $current);
if ($comparison === 0) {
printf("当前已安装 %s。\n", $target);
return;
}
if ($comparison < 0) {
throw new RuntimeException('更新目标必须高于已安装版本。');
}
if (!mkdir($work, 0700)) {
throw new RuntimeException('无法建立更新暂存目录。');
}
$base = $this->archive(self::LEGACY_BASES[$current] ?? ('v' . $current), $current, $work . '/base.zip');
$release = $this->archive($target, substr($target, 1), $work . '/release.zip');
$plan = $this->plan($base, $release, $backup);
$php = getenv('LAYSITE_PHP') ?: PHP_BINARY;
self::run([$php, 'bin/backup.php', 'export', $backup], $this->root);
$vendor = $this->stageDependencies($work, $plan, $release);
if ($plan !== $this->plan($base, $release, $backup)) {
throw new RuntimeException('准备更新期间,站点文件发生了变化。');
}
$this->apply($work, $pending, $plan, $release, $vendor, $php);
printf("已更新至 %s,可使用原站点配置启动 Webman。\n", $target);
} finally {
if (is_dir($work) && !is_file($pending)) {
self::removeDirectory($work);
}
fclose($lock);
}
}
private function version(): string
{
$version = trim((string) @file_get_contents($this->root . '/VERSION'));
if (!preg_match('/^\d+\.\d+\.\d+$/D', $version)) {
throw new RuntimeException('请从已安装 LaySite 的目录运行更新器。');
}
return $version;
}
private static function download(string $path, $stream, int $limit, int $timeout): void
{
$curl = curl_init(self::HOST . $path);
$bytes = 0;
curl_setopt_array($curl, [
CURLOPT_USERAGENT => 'LaySite release updater',
CURLOPT_CONNECTTIMEOUT_MS => min(3500, $timeout),
CURLOPT_TIMEOUT_MS => $timeout,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_WRITEFUNCTION => static function (CurlHandle $curl, string $chunk) use ($stream, $limit, &$bytes): int {
$bytes += strlen($chunk);
return $bytes > $limit ? 0 : (int) fwrite($stream, $chunk);
},
]);
if (curl_exec($curl) === false) {
throw new RuntimeException('下载 LaySite 发布文件失败。' . ($bytes > $limit ? '文件超过大小限制。' : curl_error($curl)));
}
$status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
if ($status !== 200) {
throw new RuntimeException("无法读取 LaySite 发布文件 $path(HTTP $status)。");
}
}
private function archive(string $ref, string $version, string $path): array
{
$stream = fopen($path, 'xb');
if ($stream === false) {
throw new RuntimeException('无法写入发布 ZIP。');
}
try {
self::download(self::PROJECT . "/archive/$ref.zip", $stream, self::MAX_ARCHIVE_BYTES, 60_000);
} finally {
fclose($stream);
}
$archive = new PharData($path);
$files = [];
$size = 0;
$prefix = 'phar://' . $path . '/laysite/';
foreach (new RecursiveIteratorIterator($archive) as $entry) {
$uri = $entry->getPathname();
if (!str_starts_with($uri, $prefix)) {
throw new RuntimeException('发布 ZIP 的目录结构无效。');
}
$name = substr($uri, strlen($prefix));
if ($entry->isLink() || !$entry->isFile() || str_contains($name, '\\')
|| preg_match('~(?:^|/)\.{0,2}(?:/|$)|[\x00-\x1f\x7f]~', $name)) {
throw new RuntimeException('发布 ZIP 包含无效的文件路径。');
}
$size += $entry->getSize();
if ($size > self::MAX_EXPANDED_BYTES) {
throw new RuntimeException('发布 ZIP 解压后的大小超过限制。');
}
if (!preg_match(self::MANAGED, $name)) {
continue;
}
$hash = hash_file('sha256', $uri);
if ($hash === false || isset($files[$name])) {
throw new RuntimeException('发布 ZIP 文件损坏。');
}
$files[$name] = ['uri' => $uri, 'hash' => $hash, 'mode' => $entry->getPerms() & 0777];
}
foreach (['VERSION', 'start.php', 'bin/install.php', 'composer.json', 'composer.lock', 'resources/schema.sql'] as $required) {
if (!isset($files[$required])) {
throw new RuntimeException('发布 ZIP 缺少 ' . $required);
}
}
if (trim((string) file_get_contents($files['VERSION']['uri'])) !== $version) {
throw new RuntimeException('发布 ZIP 的 VERSION 与所选版本不一致。');
}
return $files;
}
private function plan(array $base, array $release, string $backup): array
{
clearstatcache();
require_once $this->root . '/vendor/autoload.php';
$database = App\Content\Database::path();
$media = App\Content\Media::directory();
$protected = array_unique([
$database, realpath($database) ?: $database, $media, realpath($media) ?: $media, $backup,
]);
$plan = [];
$conflicts = [];
foreach (array_keys($base + $release) as $name) {
$old = $base[$name]['hash'] ?? null;
$next = $release[$name]['hash'] ?? null;
if ($old === $next) {
continue;
}
try {
$path = $this->managedPath($name);
foreach ($protected as $reserved) {
if ($path === $reserved || str_starts_with($path, rtrim($reserved, '/') . '/')
|| str_starts_with($reserved, $path . '/') || in_array($path, [$database . '.key', $database . '-wal', $database . '-shm'], true)) {
throw new RuntimeException('更新路径与站点数据重叠。');
}
}
$local = is_file($path) ? hash_file('sha256', $path) : null;
if ($local === $next) {
continue;
}
if ($local !== $old) {
$conflicts[] = $name;
continue;
}
$plan[] = $name;
} catch (RuntimeException) {
$conflicts[] = $name;
}
}
if ($conflicts !== []) {
sort($conflicts);
throw new RuntimeException("以下路径与站点定制或数据冲突,尚未替换任何文件:\n" . implode("\n", $conflicts));
}
if (array_intersect(['composer.json', 'composer.lock'], $plan)) {
$vendor = $this->root . '/vendor';
foreach ($protected as $reserved) {
if ($reserved === $vendor || str_starts_with($reserved, $vendor . '/')) {
throw new RuntimeException('站点数据或备份路径位于 vendor 目录,请先调整该路径。');
}
}
}
return $plan;
}
private function managedPath(string $name): string
{
$path = $this->root;
$parts = explode('/', $name);
$leaf = array_pop($parts);
foreach ($parts as $part) {
$path .= '/' . $part;
if (is_link($path) || (file_exists($path) && !is_dir($path))) {
throw new RuntimeException('更新路径不可写:' . $name);
}
}
$path .= '/' . $leaf;
if (is_link($path) || (file_exists($path) && !is_file($path))) {
throw new RuntimeException('更新路径不可写:' . $name);
}
return $path;
}
private function stageDependencies(string $work, array $plan, array $release): ?string
{
if (!array_intersect(['composer.json', 'composer.lock'], $plan)) {
return null;
}
$dependencies = $work . '/dependencies';
self::makeDirectory($dependencies);
foreach (['composer.json', 'composer.lock'] as $name) {
$source = in_array($name, $plan, true) ? $release[$name]['uri'] : $this->root . '/' . $name;
if (!copy($source, $dependencies . '/' . $name)) {
throw new RuntimeException('无法准备 Composer 依赖。');
}
}
$vendor = $dependencies . '/vendor';
self::run([
getenv('LAYSITE_COMPOSER') ?: 'composer', 'install', '--no-dev', '--prefer-dist',
'--no-interaction', '--no-scripts', '--no-plugins',
], $dependencies, array_replace(getenv(), ['COMPOSER' => 'composer.json', 'COMPOSER_VENDOR_DIR' => $vendor]));
if (!is_file($vendor . '/autoload.php')) {
throw new RuntimeException('Composer 没有在暂存目录生成依赖。');
}
return $vendor;
}
private function apply(string $work, string $pending, array $plan, array $release, ?string $vendor, string $php): void
{
$staged = [];
foreach ($plan as $name) {
$staged[$name] = null;
if (isset($release[$name])) {
$file = $work . '/files/' . $name;
self::makeDirectory(dirname($file));
$mode = $release[$name]['mode'] & 0755;
if ($name === 'bin/update.sh') {
$mode |= 0100;
}
if (!copy($release[$name]['uri'], $file) || !chmod($file, $mode ?: 0644)) {
throw new RuntimeException('无法暂存文件 ' . $name);
}
$staged[$name] = $file;
}
}
if ($vendor !== null) {
if (is_link($this->root . '/vendor') || !is_dir($this->root . '/vendor')) {
throw new RuntimeException('站点的 vendor 目录需要手动更新。');
}
$staged['vendor'] = $vendor;
}
$marker = fopen($pending, 'x');
if ($marker === false) {
throw new RuntimeException('无法写入更新记录。');
}
$record = $work . PHP_EOL;
$written = fwrite($marker, $record);
fclose($marker);
if ($written !== strlen($record)) {
unlink($pending);
throw new RuntimeException('无法写入完整的更新记录。');
}
$applied = [];
try {
foreach ($staged as $name => $source) {
$destination = $this->root . '/' . $name;
$previous = $work . '/previous/' . $name;
if (file_exists($destination)) {
self::makeDirectory(dirname($previous));
self::move($destination, $previous);
}
$applied[] = $name;
if ($source !== null) {
self::makeDirectory(dirname($destination));
self::move($source, $destination);
}
}
self::run([$php, 'bin/install.php'], $this->root);
} catch (Throwable $error) {
try {
foreach (array_reverse($applied) as $name) {
$path = $this->root . '/' . $name;
if (file_exists($path)) {
$discard = $work . '/discard/' . $name;
self::makeDirectory(dirname($discard));
self::move($path, $discard);
}
$previous = $work . '/previous/' . $name;
if (file_exists($previous)) {
self::move($previous, $path);
}
}
unlink($pending);
} catch (Throwable $rollback) {
throw new RuntimeException('更新回退未完成。原文件保存在 ' . $work . '。' . $rollback->getMessage(), previous: $error);
}
throw new RuntimeException('更新失败,原程序文件已恢复。' . $error->getMessage(), previous: $error);
}
unlink($pending);
}
private static function move(string $from, string $to): void
{
if (!rename($from, $to)) {
throw new RuntimeException('无法移动 ' . $from . ' 到 ' . $to);
}
}
private static function run(array $command, string $directory, ?array $environment = null): void
{
$process = proc_open($command, [STDIN, STDOUT, STDERR], $pipes, $directory, $environment);
if (!is_resource($process) || proc_close($process) !== 0) {
throw new RuntimeException('命令执行失败:' . implode(' ', array_slice($command, 0, 2)));
}
}
private static function makeDirectory(string $path): void
{
if (!is_dir($path) && !mkdir($path, 0755, true) && !is_dir($path)) {
throw new RuntimeException('无法建立目录 ' . $path);
}
}
private static function removeDirectory(string $path): void
{
$entries = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST);
foreach ($entries as $entry) {
if ($entry->isDir() && !$entry->isLink()) {
rmdir($entry->getPathname());
} else {
unlink($entry->getPathname());
}
}
rmdir($path);
}
}
umask(0027);
try {
$updater = new LaySiteUpdater(getcwd());
$target = $argv[1] ?? 'check';
if ($target === 'check' && $argc <= 2) {
$updater->check();
} elseif ($argc === 3 && preg_match('/^v\d+\.\d+\.\d+$/D', $target)) {
$backup = str_starts_with($argv[2], '/') ? $argv[2] : getcwd() . '/' . $argv[2];
$directory = realpath(dirname($backup));
if ($directory === false || !str_ends_with($backup, '.tar') || file_exists($backup) || is_link($backup)) {
throw new RuntimeException('请指定已存在的目录和一个尚未使用的 .tar 备份文件名。');
}
$updater->update($target, $directory . '/' . basename($backup));
} else {
fwrite(STDERR, "Usage: bin/update.sh check | vX.Y.Z /path/snapshot.tar\n");
exit(2);
}
} catch (Throwable $error) {
fwrite(STDERR, $error->getMessage() . PHP_EOL);
exit(1);
}
+1 -37
View File
@@ -2,40 +2,4 @@
set -eu
cd "$(dirname "$0")/.."
php_bin=${LAYSITE_PHP:-php}
composer_bin=${LAYSITE_COMPOSER:-composer}
target=${1:-check}
if [ "$target" = check ]; then
git fetch origin --tags
git describe --tags --always
git tag --list 'v[0-9]*' --sort=-version:refname | awk '/^v[0-9]+\.[0-9]+\.[0-9]+$/'
exit 0
fi
if ! printf '%s\n' "$target" | grep -Eq '^v[0-9]+\.[0-9]+\.[0-9]+$' || [ "$#" -ne 2 ]; then
printf '%s\n' 'Usage: bin/update.sh check | vX.Y.Z /path/snapshot.tar' >&2
exit 2
fi
if [ -n "$(git status --porcelain)" ]; then
printf '%s\n' 'Commit or set aside local source changes before updating.' >&2
exit 1
fi
git fetch origin --tags
current=$(git rev-parse HEAD)
next=$(git rev-parse --verify "refs/tags/$target^{commit}")
git merge-base --is-ancestor "$current" "$next"
"$php_bin" bin/backup.php export "$2"
if git switch --detach "$next" &&
"$composer_bin" install --no-dev --prefer-dist --no-interaction --no-scripts &&
"$php_bin" bin/install.php
then
printf 'Updated to %s. Start Webman with the original site environment.\n' "$target"
else
git switch --detach "$current"
"$composer_bin" install --no-dev --prefer-dist --no-interaction --no-scripts
printf 'Update failed. The prior source version is checked out and the backup is at %s.\n' "$2" >&2
exit 1
fi
exec "${LAYSITE_PHP:-php}" bin/update.php "$@"