Compare commits

..
Author SHA1 Message Date
Qiufeng cea7048f6c fix: make online updates observable and recoverable
Release / release (push) Canceled after 0s
2026-08-18 12:56:14 +08:00
Qiufeng 10d2e2f0d1 fix: leave setup wizard after completion
Release / release (push) Canceled after 0s
2026-08-18 11:38:28 +08:00
Qiufeng bb5e63aaf0 fix: force-stop service account during purge 2026-08-18 11:24:57 +08:00
Qiufeng 2cf29c030a fix: recover stalled update requests
Release / release (push) Canceled after 0s
2026-08-18 09:33:06 +08:00
Qiufeng 6d4ae00ae0 feat: split online update into explicit stages
Release / release (push) Canceled after 0s
2026-08-18 09:01:34 +08:00
Qiufeng 3c7847c8f5 docs: point preview install example to latest release 2026-08-18 08:05:40 +08:00
24 changed files with 1569 additions and 163 deletions
+18 -13
View File
@@ -56,7 +56,7 @@ PostgreSQL 18 兼容工作继续冻结。
先在宝塔面板停止并删除当前错误的 Java 项目,再执行: 先在宝塔面板停止并删除当前错误的 Java 项目,再执行:
```bash ```bash
curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.26/install.sh | sudo env KAIDI_APP_PORT=18080 bash curl -fsSL https://git.awaioi.com/ERP-Team/kaidi/releases/download/v1.0.0-preview.30/install.sh | sudo env KAIDI_APP_PORT=18080 bash
``` ```
该命令只安装程序运行所需的 systemd 单元,自动创建 `kaidi` 用户并检测现有 Java 17(包括 该命令只安装程序运行所需的 systemd 单元,自动创建 `kaidi` 用户并检测现有 Java 17(包括
@@ -189,7 +189,8 @@ systemctl is-enabled kaidi-update.path
#### 5. 后台在线更新 #### 5. 后台在线更新
初始化脚本已启用 `kaidi-update.path`,后台“系统治理 → 系统更新”流程保持不变:点击“获取更新”下载并验签,确认后点击“立即重启”。 初始化脚本已启用 `kaidi-update.path`。后台“系统治理 → 系统更新”按明确阶段执行:点击“获取版本”只读取版本信息,
发现新版本后点击“立即更新”才开始下载和验签;页面显示“下载完成”后,再点击“立即更新并重启”。
root 更新器原子切换 `/www/wwwroot/kaidi/current`,向当前 Java 进程发送停止信号;宝塔的意外重启守护随后按新 `current` 链接拉起 Java, root 更新器原子切换 `/www/wwwroot/kaidi/current`,向当前 Java 进程发送停止信号;宝塔的意外重启守护随后按新 `current` 链接拉起 Java,
健康检查通过后页面等待 10 秒并自动刷新。更新器不会安装或启动 `kaidi-finance.service`,也不会修改 Nginx。 健康检查通过后页面等待 10 秒并自动刷新。更新器不会安装或启动 `kaidi-finance.service`,也不会修改 Nginx。
@@ -245,12 +246,13 @@ git push origin v1.0.0-preview.25
更新流程固定为: 更新流程固定为:
1. 点击“获取更新”,后端排队 `DOWNLOAD`;更新器下载 manifest、签名和应用包,执行 RSA、SHA-256、版本、文件名和压缩包路径校验, 1. 点击“获取版本”,只实时请求 Gitea Latest Release 版本、发布时间和发布说明,不排队下载。
通过后缓存到 `/var/lib/kaidi-update/cache/<version>`,业务服务继续运行。 2. 发现新版本后显示“立即更新”;管理员点击后才排队 `DOWNLOAD`。更新器下载 manifest、签名和应用包,执行 RSA、SHA-256、版本、
2. 页面显示 `READY/等待重启` 后才出现“立即重启”;未缓存或版本不一致的包不能进入安装。 文件名和压缩包路径校验,通过后缓存到 `/var/lib/kaidi-update/cache/<version>`,业务服务继续运行。
3. 管理员点击“立即重启”,更新器预先调用宿主机已有的 `mysqldump`,备份权限为 `0600`,默认保留最近 5 份;程序不会安装 MySQL 或客户端。 3. 页面实时轮询并依次显示下载已排队、下载中、校验中和 `READY/下载完成`;只有下载完成后才显示“立即更新并重启”。
4. 更新器安装并保护新版本目录,原子切换 `/www/wwwroot/kaidi/current`,校验旧 Java 的受控 PID 后发送停止信号;宝塔守护自动启动新版本。 4. 管理员点击“立即更新并重启”,更新器预先调用宿主机已有的 `mysqldump`,备份权限为 `0600`,默认保留最近 5 份;程序不会安装 MySQL 或客户端。
5. 健康端点、静态首页和运行版本全部通过后,页面等待 10 秒自动刷新;期间断线由前端轮询恢复。任一检查失败则切回上一应用版本, 5. 更新器安装并保护新版本目录,原子切换 `/www/wwwroot/kaidi/current`,校验旧 Java 的受控 PID 后发送停止信号;宝塔守护自动启动新版本。
6. 健康端点、静态首页和运行版本全部通过后,页面等待 10 秒自动刷新;期间断线或命令响应丢失由前端状态重同步恢复。任一检查失败则切回上一应用版本,
保留数据库备份和事务证据供人工处理。 保留数据库备份和事务证据供人工处理。
忙碌期间检查、下载和安装按钮保持禁用,防止重复请求;10 秒只用于成功后的页面刷新,不延迟服务端切换。数据库迁移必须至少保持一个版本向后兼容。 忙碌期间检查、下载和安装按钮保持禁用,防止重复请求;10 秒只用于成功后的页面刷新,不延迟服务端切换。数据库迁移必须至少保持一个版本向后兼容。
@@ -262,19 +264,22 @@ sudo journalctl -u kaidi-update.service -n 100 --no-pager
cat /var/lib/kaidi-update/status.json cat /var/lib/kaidi-update/status.json
``` ```
如果 `status.json` 显示 `FAILED` 且日志提示回滚未完成,失败请求会归档到 进程被中断时,`kaidi-update.path` 会根据 `processing/request.json` 或 `transactions/active` 自动恢复一次。
`/var/lib/kaidi-update/failed`,活动事务保留在 `transactions/active`,系统不会自动重复安装。修复日志所示的 如果 `status.json` 显示 `RECOVERY_REQUIRED`,失败请求会归档到 `/var/lib/kaidi-update/failed`,事务证据会移到
磁盘、权限或旧版本健康问题后,才明确执行一次: `transactions/recovery-required*` 并退出自动触发路径,新下载和安装请求也会被拒绝。修复日志所示的磁盘、权限或
旧版本健康问题后,将唯一一份待恢复事务移回 `active`,再明确执行一次:
```bash ```bash
sudo mv /var/lib/kaidi-update/transactions/recovery-required /var/lib/kaidi-update/transactions/active
sudo systemctl reset-failed kaidi-update.service kaidi-update.path sudo systemctl reset-failed kaidi-update.service kaidi-update.path
sudo systemctl start kaidi-update.service sudo systemctl start kaidi-update.service
sudo journalctl -u kaidi-update.service -n 100 --no-pager sudo journalctl -u kaidi-update.service -n 100 --no-pager
cat /var/lib/kaidi-update/status.json cat /var/lib/kaidi-update/status.json
``` ```
只有状态恢复为 `SUCCEEDED`、`CURRENT` 或确定性的终态 `FAILED`,且 `transactions/active` 已处理完成后, 如果目录带时间后缀,先通过 `ls -1d /var/lib/kaidi-update/transactions/recovery-required*` 确认唯一目录,再替换上面
才算本次恢复结束。后台会保留真实失败状态,不会把待恢复的 processing 请求误显示成普通排队。 命令中的源路径。只有状态恢复为 `SUCCEEDED`、`CURRENT` 或确定性的终态 `FAILED`,且 `transactions/active` 已处理
完成后,才算本次恢复结束。后台会保留真实失败状态,不会把待恢复请求误显示成普通排队。
## 手工生成 Release ## 手工生成 Release
@@ -0,0 +1,11 @@
package com.kaidi.finance.update.api;
import java.time.Instant;
public record SystemUpdateEventView(
Instant occurredAt,
String level,
String stage,
String message
) {
}
@@ -14,6 +14,12 @@ public record SystemUpdateView(
Instant publishedAt, Instant publishedAt,
Instant checkedAt, Instant checkedAt,
Instant statusUpdatedAt, Instant statusUpdatedAt,
Long downloadedBytes,
Long totalBytes,
Long bytesPerSecond,
Integer downloadPercent,
Integer restartExpectedSeconds,
List<SystemUpdateEventView> events,
List<String> allowedActions List<String> allowedActions
) { ) {
} }
@@ -11,6 +11,7 @@ import com.kaidi.finance.shared.security.AuthorizationService;
import com.kaidi.finance.shared.security.IdentityContext; import com.kaidi.finance.shared.security.IdentityContext;
import com.kaidi.finance.update.api.SystemUpdateContracts.DownloadUpdateRequest; import com.kaidi.finance.update.api.SystemUpdateContracts.DownloadUpdateRequest;
import com.kaidi.finance.update.api.SystemUpdateContracts.InstallUpdateRequest; import com.kaidi.finance.update.api.SystemUpdateContracts.InstallUpdateRequest;
import com.kaidi.finance.update.api.SystemUpdateEventView;
import com.kaidi.finance.update.api.SystemUpdateView; import com.kaidi.finance.update.api.SystemUpdateView;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
@@ -44,6 +45,8 @@ public class SystemUpdateApplicationService {
private static final int MAX_MANIFEST_BYTES = 64 * 1024; private static final int MAX_MANIFEST_BYTES = 64 * 1024;
private static final int MAX_RELEASE_API_BYTES = 256 * 1024; private static final int MAX_RELEASE_API_BYTES = 256 * 1024;
private static final int MAX_STATUS_BYTES = 64 * 1024; private static final int MAX_STATUS_BYTES = 64 * 1024;
private static final int MAX_EVENT_LOG_BYTES = 256 * 1024;
private static final int MAX_EVENT_COUNT = 120;
private static final int MAX_REDIRECTS = 3; private static final int MAX_REDIRECTS = 3;
private static final String PRERELEASE_IDENTIFIER = private static final String PRERELEASE_IDENTIFIER =
"(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)"; "(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)";
@@ -57,8 +60,8 @@ public class SystemUpdateApplicationService {
"^(.*/)?api/v1/repos/([A-Za-z0-9._-]+)/([A-Za-z0-9._-]+)/releases/(?:latest|tags/[^/?#]+)$"); "^(.*/)?api/v1/repos/([A-Za-z0-9._-]+)/([A-Za-z0-9._-]+)/releases/(?:latest|tags/[^/?#]+)$");
private static final Pattern GITEA_RELEASE_TAG = Pattern.compile("^v[0-9A-Za-z][0-9A-Za-z._+-]{0,127}$"); private static final Pattern GITEA_RELEASE_TAG = Pattern.compile("^v[0-9A-Za-z][0-9A-Za-z._+-]{0,127}$");
private static final List<String> BUSY_STATES = List.of( private static final List<String> BUSY_STATES = List.of(
"QUEUED", "DOWNLOAD_QUEUED", "INSTALL_QUEUED", "VERIFYING", "DOWNLOADING", "BACKING_UP", "QUEUED", "DOWNLOAD_QUEUED", "INSTALL_QUEUED", "PRECHECKING", "VERIFYING", "DOWNLOADING",
"INSTALLING", "RUNNING"); "BACKING_UP", "INSTALLING", "RUNNING");
private final SystemUpdateProperties properties; private final SystemUpdateProperties properties;
private final AuthorizationService authorizationService; private final AuthorizationService authorizationService;
@@ -353,6 +356,10 @@ public class SystemUpdateApplicationService {
try (FileChannel channel = FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE); try (FileChannel channel = FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
FileLock ignored = channel.lock()) { FileLock ignored = channel.lock()) {
UpdateStatus currentStatus = readStatus(); UpdateStatus currentStatus = readStatus();
if ("RECOVERY_REQUIRED".equals(currentStatus.state())) {
throw new BusinessException(HttpStatus.CONFLICT, ErrorCode.COMMAND_IN_PROGRESS,
"更新服务需要人工恢复,暂不接受新的更新请求");
}
if (BUSY_STATES.contains(currentStatus.state())) { if (BUSY_STATES.contains(currentStatus.state())) {
throw new BusinessException(HttpStatus.CONFLICT, ErrorCode.COMMAND_IN_PROGRESS, throw new BusinessException(HttpStatus.CONFLICT, ErrorCode.COMMAND_IN_PROGRESS,
"已有系统更新任务正在执行"); "已有系统更新任务正在执行");
@@ -421,7 +428,10 @@ public class SystemUpdateApplicationService {
String state = root.path("state").asText("UNKNOWN").toUpperCase(Locale.ROOT); String state = root.path("state").asText("UNKNOWN").toUpperCase(Locale.ROOT);
if (!state.matches("^[A-Z_]{2,32}$")) state = "UNKNOWN"; if (!state.matches("^[A-Z_]{2,32}$")) state = "UNKNOWN";
return new UpdateStatus(state, root.path("message").asText(""), return new UpdateStatus(state, root.path("message").asText(""),
blank(root.path("targetVersion").asText(null)), parseInstant(root.path("updatedAt").asText(null))); blank(root.path("targetVersion").asText(null)), parseInstant(root.path("updatedAt").asText(null)),
nonNegativeLong(root, "downloadedBytes"), nonNegativeLong(root, "totalBytes"),
nonNegativeLong(root, "bytesPerSecond"), boundedInteger(root, "downloadPercent", 0, 100),
boundedInteger(root, "restartExpectedSeconds", 0, 300));
} catch (IOException exception) { } catch (IOException exception) {
return new UpdateStatus("UNKNOWN", "更新状态读取失败", null, null); return new UpdateStatus("UNKNOWN", "更新状态读取失败", null, null);
} }
@@ -433,17 +443,60 @@ public class SystemUpdateApplicationService {
String candidateVersion = manifest == null ? status.targetVersion() : manifest.version(); String candidateVersion = manifest == null ? status.targetVersion() : manifest.version();
boolean available = candidateVersion != null && compareVersions(candidateVersion, current) > 0; boolean available = candidateVersion != null && compareVersions(candidateVersion, current) > 0;
boolean busy = BUSY_STATES.contains(status.state()); boolean busy = BUSY_STATES.contains(status.state());
boolean recoveryRequired = "RECOVERY_REQUIRED".equals(status.state());
boolean pending = hasPendingRequest(properties.requestFile().toAbsolutePath().normalize()); boolean pending = hasPendingRequest(properties.requestFile().toAbsolutePath().normalize());
boolean ready = "READY".equals(status.state()) && candidateVersion != null boolean ready = "READY".equals(status.state()) && candidateVersion != null
&& candidateVersion.equals(status.targetVersion()); && candidateVersion.equals(status.targetVersion());
List<String> actions = new ArrayList<>(); List<String> actions = new ArrayList<>();
if (enabled && !busy && !pending) actions.add("CHECK"); if (enabled && !busy && !pending && !recoveryRequired) actions.add("CHECK");
if (enabled && available && !busy && !pending && authorizationService.hasPermission("admin:update:execute")) { if (enabled && available && !busy && !pending && !recoveryRequired
&& authorizationService.hasPermission("admin:update:execute")) {
actions.add(ready ? "INSTALL" : "DOWNLOAD"); actions.add(ready ? "INSTALL" : "DOWNLOAD");
} }
return new SystemUpdateView(enabled, current, candidateVersion, return new SystemUpdateView(enabled, current, candidateVersion,
available, status.state(), status.message(), manifest == null ? null : manifest.releaseNotes(), available, status.state(), status.message(), manifest == null ? null : manifest.releaseNotes(),
manifest == null ? null : manifest.publishedAt(), lastCheckedAt, status.updatedAt(), List.copyOf(actions)); manifest == null ? null : manifest.publishedAt(), lastCheckedAt, status.updatedAt(),
status.downloadedBytes(), status.totalBytes(), status.bytesPerSecond(), status.downloadPercent(),
status.restartExpectedSeconds(), readUpdateEvents(), List.copyOf(actions));
}
private List<SystemUpdateEventView> readUpdateEvents() {
Path statusFile = properties.statusFile().toAbsolutePath().normalize();
Path parent = statusFile.getParent();
if (parent == null) return List.of();
Path eventFile = parent.resolve("events.jsonl").normalize();
if (!eventFile.startsWith(parent) || !Files.isRegularFile(eventFile, LinkOption.NOFOLLOW_LINKS)
|| Files.isSymbolicLink(eventFile)) {
return List.of();
}
try {
if (Files.size(eventFile) > MAX_EVENT_LOG_BYTES) return List.of();
List<String> lines = Files.readAllLines(eventFile, StandardCharsets.UTF_8);
int first = Math.max(0, lines.size() - MAX_EVENT_COUNT);
List<SystemUpdateEventView> events = new ArrayList<>();
for (int index = first; index < lines.size(); index++) {
String line = lines.get(index);
if (line.isBlank() || line.length() > 4096) continue;
try {
JsonNode event = objectMapper.readTree(line);
Instant occurredAt = parseInstant(event.path("occurredAt").asText(null));
String level = event.path("level").asText("INFO").toUpperCase(Locale.ROOT);
String stage = event.path("stage").asText("UNKNOWN").toUpperCase(Locale.ROOT);
String message = event.path("message").asText("");
if (occurredAt == null || !level.matches("^(INFO|WARN|ERROR)$")
|| !stage.matches("^[A-Z_]{2,32}$") || message.isBlank()) {
continue;
}
events.add(new SystemUpdateEventView(occurredAt, level, stage,
message.length() > 1000 ? message.substring(0, 1000) : message));
} catch (IOException ignored) {
// Ignore a partially written event line.
}
}
return List.copyOf(events);
} catch (IOException exception) {
return List.of();
}
} }
private boolean hasPendingRequest(Path requestFile) { private boolean hasPendingRequest(Path requestFile) {
@@ -564,6 +617,20 @@ public class SystemUpdateApplicationService {
} }
} }
private static Long nonNegativeLong(JsonNode root, String field) {
JsonNode value = root.path(field);
if (!value.canConvertToLong()) return null;
long parsed = value.asLong();
return parsed < 0 ? null : parsed;
}
private static Integer boundedInteger(JsonNode root, String field, int minimum, int maximum) {
JsonNode value = root.path(field);
if (!value.canConvertToInt()) return null;
int parsed = value.asInt();
return parsed < minimum || parsed > maximum ? null : parsed;
}
private BusinessException validation(String message) { private BusinessException validation(String message) {
return new BusinessException(HttpStatus.UNPROCESSABLE_ENTITY, ErrorCode.VALIDATION_FAILED, message); return new BusinessException(HttpStatus.UNPROCESSABLE_ENTITY, ErrorCode.VALIDATION_FAILED, message);
} }
@@ -580,7 +647,12 @@ public class SystemUpdateApplicationService {
String releaseNotes) { String releaseNotes) {
} }
private record UpdateStatus(String state, String message, String targetVersion, Instant updatedAt) { private record UpdateStatus(String state, String message, String targetVersion, Instant updatedAt,
Long downloadedBytes, Long totalBytes, Long bytesPerSecond,
Integer downloadPercent, Integer restartExpectedSeconds) {
private UpdateStatus(String state, String message, String targetVersion, Instant updatedAt) {
this(state, message, targetVersion, updatedAt, null, null, null, null, null);
}
} }
private record QueueTransition(UpdateStatus previous, UpdateStatus queued) { private record QueueTransition(UpdateStatus previous, UpdateStatus queued) {
@@ -211,6 +211,81 @@ class SystemUpdateApplicationServiceTest {
} }
} }
@Test
void restoresDownloadMetricsAndRuntimeEventsFromUpdaterState() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
Path inbox = Files.createDirectory(tempDir.resolve("progress-inbox"));
Path statusFile = tempDir.resolve("progress-status.json");
Files.writeString(statusFile, """
{"state":"DOWNLOADING","message":"Downloading signed release","targetVersion":"1.0.0-preview.2",
"updatedAt":"2026-08-18T03:00:00Z","downloadedBytes":5242880,"totalBytes":10485760,
"bytesPerSecond":1048576,"downloadPercent":50,"restartExpectedSeconds":10}
""");
Files.writeString(tempDir.resolve("events.jsonl"), """
{"occurredAt":"2026-08-18T02:59:59Z","level":"INFO","stage":"VERIFYING","message":"签名校验开始"}
{"occurredAt":"2026-08-18T03:00:00Z","level":"INFO","stage":"DOWNLOADING","message":"更新包下载中"}
""");
SystemUpdateApplicationService service = serviceForGitea(server, inbox, statusFile);
var status = service.status();
assertEquals("DOWNLOADING", status.state());
assertEquals(5_242_880L, status.downloadedBytes());
assertEquals(10_485_760L, status.totalBytes());
assertEquals(1_048_576L, status.bytesPerSecond());
assertEquals(50, status.downloadPercent());
assertEquals(10, status.restartExpectedSeconds());
assertEquals(2, status.events().size());
assertEquals("DOWNLOADING", status.events().get(1).stage());
assertFalse(status.allowedActions().contains("DOWNLOAD"));
}
@Test
void recoveryRequiredStateBlocksEveryUpdateAction() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
server.createContext("/api/v1/repos/ERP-Team/kaidi/releases/latest", exchange -> {
String assetUrl = "http://127.0.0.1:" + server.getAddress().getPort()
+ "/ERP-Team/kaidi/releases/download/v1.0.0-preview.2/release-manifest.json";
byte[] body = """
{"tag_name":"v1.0.0-preview.2","assets":[
{"name":"release-manifest.json","browser_download_url":"%s"}]}
""".formatted(assetUrl).getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.createContext("/ERP-Team/kaidi/releases/download/v1.0.0-preview.2/release-manifest.json",
exchange -> {
byte[] body = """
{"version":"1.0.0-preview.2","artifact":"kaidi-finance-1.0.0-preview.2.tar.gz",
"sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}
""".getBytes(StandardCharsets.UTF_8);
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
Path inbox = Files.createDirectory(tempDir.resolve("recovery-inbox"));
Path statusFile = tempDir.resolve("recovery-status.json");
Files.writeString(statusFile, """
{"state":"RECOVERY_REQUIRED","message":"自动回滚未完成","targetVersion":"1.0.0-preview.2",
"updatedAt":"2026-08-18T03:10:00Z"}
""");
SystemUpdateApplicationService service = serviceForGitea(server, inbox, statusFile);
try {
var status = service.status();
assertEquals("RECOVERY_REQUIRED", status.state());
assertTrue(status.allowedActions().isEmpty());
assertThrows(BusinessException.class,
() -> service.download(new DownloadUpdateRequest("1.0.0-preview.2")));
assertFalse(Files.exists(inbox.resolve("request.json")));
} finally {
server.stop(0);
}
}
@Test @Test
void checksConfiguredManifestAndQueuesOnlyItsLatestVersion() throws Exception { void checksConfiguredManifestAndQueuesOnlyItsLatestVersion() throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
+1 -1
View File
@@ -95,7 +95,7 @@ main() {
[ "$(uname -s)" = Linux ] || die "Baota initialization only supports Linux" [ "$(uname -s)" = Linux ] || die "Baota initialization only supports Linux"
command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ] \ command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ] \
|| die "systemd is required for the privileged background updater" || die "systemd is required for the privileged background updater"
for command in find openssl sha256sum; do for command in find openssl setsid sha256sum; do
command -v "$command" >/dev/null 2>&1 || die "$command is required" command -v "$command" >/dev/null 2>&1 || die "$command is required"
done done
+77 -8
View File
@@ -67,8 +67,61 @@ related_pids() {
done done
} }
managed_service_account() {
local entry home shell
entry=$(getent passwd "$SERVICE_USER" 2>/dev/null || true)
[ -n "$entry" ] || return 1
home=$(printf '%s\n' "$entry" | awk -F: '{print $6}')
shell=$(printf '%s\n' "$entry" | awk -F: '{print $7}')
case "$home:$shell" in
"$STATE_ROOT:"*/nologin|"$STATE_ROOT:"*/false) return 0 ;;
*) return 1 ;;
esac
}
service_user_pids() {
local uid=$1 proc pid owner_uid
for proc in /proc/[0-9]*; do
[ -d "$proc" ] || continue
pid=${proc##*/}
owner_uid=$(stat -c '%u' "$proc" 2>/dev/null || true)
[ "$owner_uid" = "$uid" ] && printf '%s\n' "$pid"
done
}
terminate_uid_processes() {
local uid=$1 deadline
local -a pids=()
mapfile -t pids < <(service_user_pids "$uid")
if [ "${#pids[@]}" -gt 0 ]; then
log "Stopping processes owned by the dedicated $SERVICE_USER account: ${pids[*]}"
kill -TERM "${pids[@]}" 2>/dev/null || true
fi
deadline=$((SECONDS + 5))
while [ "$SECONDS" -lt "$deadline" ]; do
mapfile -t pids < <(service_user_pids "$uid")
[ "${#pids[@]}" -gt 0 ] || return 0
sleep 1
done
kill -KILL "${pids[@]}" 2>/dev/null || true
sleep 1
mapfile -t pids < <(service_user_pids "$uid")
[ "${#pids[@]}" -eq 0 ]
}
all_pids_owned_by_service_user() {
local service_uid pid owner_uid
managed_service_account || return 1
service_uid=$(id -u "$SERVICE_USER")
for pid in "$@"; do
[ -d "/proc/$pid" ] || continue
owner_uid=$(stat -c '%u' "/proc/$pid" 2>/dev/null || true)
[ "$owner_uid" = "$service_uid" ] || return 1
done
}
stop_managed_processes() { stop_managed_processes() {
local deadline local allow_service_restart=${1:-false} deadline
local -a pids=() local -a pids=()
mapfile -t pids < <(related_pids) mapfile -t pids < <(related_pids)
if [ "${#pids[@]}" -gt 0 ]; then if [ "${#pids[@]}" -gt 0 ]; then
@@ -84,8 +137,12 @@ stop_managed_processes() {
kill -KILL "${pids[@]}" 2>/dev/null || true kill -KILL "${pids[@]}" 2>/dev/null || true
sleep 1 sleep 1
mapfile -t pids < <(related_pids) mapfile -t pids < <(related_pids)
[ "${#pids[@]}" -eq 0 ] \ [ "${#pids[@]}" -eq 0 ] && return 0
|| die "A process manager is restarting Kaidi; remove the Kaidi project from Baota and run this command again" if [ "$allow_service_restart" = true ] && all_pids_owned_by_service_user "${pids[@]}"; then
log "A process manager restarted the dedicated $SERVICE_USER account; forced account cleanup will stop it"
return 0
fi
die "A process manager is restarting Kaidi; remove the Kaidi project from Baota and run this command again"
} }
create_recovery_backup() { create_recovery_backup() {
@@ -120,6 +177,10 @@ create_recovery_backup() {
remove_systemd_units() { remove_systemd_units() {
local unit local unit
rm -rf \
/etc/systemd/system/kaidi-finance.service.d \
/etc/systemd/system/kaidi-update.service.d \
/etc/systemd/system/kaidi-update.path.d
rm -f \ rm -f \
/etc/systemd/system/kaidi-finance.service \ /etc/systemd/system/kaidi-finance.service \
/etc/systemd/system/kaidi-update.service \ /etc/systemd/system/kaidi-update.service \
@@ -149,15 +210,23 @@ remove_download_archives() {
} }
remove_service_identity() { remove_service_identity() {
local entry home shell group_entry gid members primary_users local entry home shell service_uid group_entry gid members primary_users
entry=$(getent passwd "$SERVICE_USER" 2>/dev/null || true) entry=$(getent passwd "$SERVICE_USER" 2>/dev/null || true)
if [ -n "$entry" ]; then if [ -n "$entry" ]; then
home=$(printf '%s\n' "$entry" | awk -F: '{print $6}') home=$(printf '%s\n' "$entry" | awk -F: '{print $6}')
shell=$(printf '%s\n' "$entry" | awk -F: '{print $7}') shell=$(printf '%s\n' "$entry" | awk -F: '{print $7}')
case "$home:$shell" in case "$home:$shell" in
"$STATE_ROOT:"*/nologin|"$STATE_ROOT:"*/false) "$STATE_ROOT:"*/nologin|"$STATE_ROOT:"*/false)
userdel "$SERVICE_USER" \ service_uid=$(id -u "$SERVICE_USER")
|| die "Failed to remove the dedicated $SERVICE_USER service account" terminate_uid_processes "$service_uid" || true
if ! userdel --force "$SERVICE_USER"; then
terminate_uid_processes "$service_uid" || true
userdel --force "$SERVICE_USER" \
|| die "Failed to remove the dedicated $SERVICE_USER service account"
fi
terminate_uid_processes "$service_uid" \
|| die "Processes owned by the removed $SERVICE_USER account are still running"
rm -rf "/run/user/$service_uid"
;; ;;
*) *)
log "Keeping pre-existing user $SERVICE_USER because its home or shell is not Kaidi-managed" log "Keeping pre-existing user $SERVICE_USER because its home or shell is not Kaidi-managed"
@@ -182,13 +251,13 @@ main() {
validate_inputs validate_inputs
log "External MySQL data and reverse-proxy configuration will not be modified" log "External MySQL data and reverse-proxy configuration will not be modified"
stop_systemd_units stop_systemd_units
stop_managed_processes stop_managed_processes true
create_recovery_backup create_recovery_backup
remove_systemd_units remove_systemd_units
remove_managed_paths remove_managed_paths
remove_download_archives remove_download_archives
remove_service_identity remove_service_identity
stop_managed_processes stop_managed_processes false
log "Local Kaidi installation state has been removed" log "Local Kaidi installation state has been removed"
if [ -n "$BACKUP_ARCHIVE" ]; then if [ -n "$BACKUP_ARCHIVE" ]; then
log "Recovery backup: $BACKUP_ARCHIVE" log "Recovery backup: $BACKUP_ARCHIVE"
+2
View File
@@ -4,6 +4,8 @@ Description=Watch for Kaidi Finance update requests
[Path] [Path]
PathChanged=/var/lib/kaidi-update/inbox PathChanged=/var/lib/kaidi-update/inbox
PathExists=/var/lib/kaidi-update/inbox/request.json PathExists=/var/lib/kaidi-update/inbox/request.json
PathExists=/var/lib/kaidi-update/processing/request.json
PathExists=/var/lib/kaidi-update/transactions/active
Unit=kaidi-update.service Unit=kaidi-update.service
[Install] [Install]
+1 -1
View File
@@ -18,5 +18,5 @@ IOSchedulingPriority=6
PrivateTmp=true PrivateTmp=true
ProtectHome=true ProtectHome=true
ProtectSystem=full ProtectSystem=full
ReadWritePaths=/opt/kaidi /www/wwwroot/kaidi /var/lib/kaidi /var/lib/kaidi-update /var/log/kaidi /etc/systemd/system ReadWritePaths=/opt/kaidi -/www/wwwroot/kaidi /var/lib/kaidi /var/lib/kaidi-update /var/log/kaidi /etc/systemd/system
UMask=0077 UMask=0077
+256 -14
View File
@@ -12,6 +12,7 @@ FAILED_REQUEST_ROOT=${KAIDI_UPDATE_FAILED_ROOT:-$STATE_ROOT/failed}
TRANSACTION_ROOT=${KAIDI_UPDATE_TRANSACTION_ROOT:-$STATE_ROOT/transactions} TRANSACTION_ROOT=${KAIDI_UPDATE_TRANSACTION_ROOT:-$STATE_ROOT/transactions}
ACTIVE_TRANSACTION=$TRANSACTION_ROOT/active ACTIVE_TRANSACTION=$TRANSACTION_ROOT/active
STATUS_FILE=${UPDATE_STATUS_FILE:-$STATE_ROOT/status.json} STATUS_FILE=${UPDATE_STATUS_FILE:-$STATE_ROOT/status.json}
EVENT_LOG_FILE=${UPDATE_EVENT_LOG_FILE:-$STATE_ROOT/events.jsonl}
PUBLIC_KEY=${UPDATE_PUBLIC_KEY:-/etc/kaidi/release-public.pem} PUBLIC_KEY=${UPDATE_PUBLIC_KEY:-/etc/kaidi/release-public.pem}
RELEASE_BASE_URL=${UPDATE_RELEASE_BASE_URL:-} RELEASE_BASE_URL=${UPDATE_RELEASE_BASE_URL:-}
RELEASE_API_URL=${UPDATE_RELEASE_API_URL:-} RELEASE_API_URL=${UPDATE_RELEASE_API_URL:-}
@@ -39,6 +40,10 @@ CACHE_TEMP=
RELEASE_AUTH_HEADER_FILE= RELEASE_AUTH_HEADER_FILE=
TARGET_VERSION= TARGET_VERSION=
TERMINAL_STATUS_WRITTEN=false TERMINAL_STATUS_WRITTEN=false
DOWNLOAD_PID=
DOWNLOAD_PGID=
LAST_DOWNLOAD_SPEED=0
SURFACE_FAILURE=
case "$HEALTH_ATTEMPTS:$HEALTH_INTERVAL_SECONDS" in case "$HEALTH_ATTEMPTS:$HEALTH_INTERVAL_SECONDS" in
*[!0-9:]* | :* | *:) printf '%s\n' "Update health-check settings must be non-negative integers" >&2; exit 1 ;; *[!0-9:]* | :* | *:) printf '%s\n' "Update health-check settings must be non-negative integers" >&2; exit 1 ;;
@@ -62,6 +67,9 @@ case "$RUNTIME_ENV_FILE" in
esac esac
bootstrap_die() { bootstrap_die() {
if [ -f "$PROCESSING_FILE" ] && [ ! -L "$PROCESSING_FILE" ]; then
fail "$1"
fi
printf '%s\n' "$1" >&2 printf '%s\n' "$1" >&2
exit 1 exit 1
} }
@@ -92,7 +100,8 @@ load_runtime_database_env() {
runtime_size=$(wc -c < "$RUNTIME_ENV_FILE" | tr -d '[:space:]') runtime_size=$(wc -c < "$RUNTIME_ENV_FILE" | tr -d '[:space:]')
[ "$runtime_size" -le 65536 ] \ [ "$runtime_size" -le 65536 ] \
|| bootstrap_die "Setup runtime environment is too large" || bootstrap_die "Setup runtime environment is too large"
runtime_owner=$(stat -c '%u' "$RUNTIME_ENV_FILE" 2>/dev/null || true) runtime_owner=$(stat -c '%u' "$RUNTIME_ENV_FILE" 2>/dev/null \
|| stat -f '%u' "$RUNTIME_ENV_FILE" 2>/dev/null || true)
service_uid=$(id -u "$SERVICE_USER" 2>/dev/null || true) service_uid=$(id -u "$SERVICE_USER" 2>/dev/null || true)
[ "$runtime_owner" = 0 ] || [ "$runtime_owner" = "$service_uid" ] \ [ "$runtime_owner" = 0 ] || [ "$runtime_owner" = "$service_uid" ] \
|| bootstrap_die "Setup runtime environment has an unexpected owner" || bootstrap_die "Setup runtime environment has an unexpected owner"
@@ -113,6 +122,7 @@ load_runtime_database_env() {
KAIDI_DB_NAME) KAIDI_DB_NAME=$runtime_value; export KAIDI_DB_NAME ;; KAIDI_DB_NAME) KAIDI_DB_NAME=$runtime_value; export KAIDI_DB_NAME ;;
KAIDI_DB_USERNAME) KAIDI_DB_USERNAME=$runtime_value; export KAIDI_DB_USERNAME ;; KAIDI_DB_USERNAME) KAIDI_DB_USERNAME=$runtime_value; export KAIDI_DB_USERNAME ;;
KAIDI_DB_PASSWORD) KAIDI_DB_PASSWORD=$runtime_value; export KAIDI_DB_PASSWORD ;; KAIDI_DB_PASSWORD) KAIDI_DB_PASSWORD=$runtime_value; export KAIDI_DB_PASSWORD ;;
DB_URL) KAIDI_DB_URL=$runtime_value; export KAIDI_DB_URL ;;
esac esac
done < "$RUNTIME_ENV_FILE" done < "$RUNTIME_ENV_FILE"
@@ -123,20 +133,84 @@ load_runtime_database_env() {
|| bootstrap_die "Setup runtime database port is invalid" || bootstrap_die "Setup runtime database port is invalid"
} }
validate_runtime_database_config() {
[ -e "$RUNTIME_ENV_FILE" ] || return 0
[ -n "${KAIDI_DB_URL:-}" ] \
|| fail "Database configuration is invalid: DB_URL is missing; application was not restarted"
[ -n "${KAIDI_DB_HOST:-}" ] && [ -n "${KAIDI_DB_NAME:-}" ] \
|| fail "Database configuration is invalid: database host and name are missing; application was not restarted"
expected_url_prefix="jdbc:mysql://${KAIDI_DB_HOST}:${KAIDI_DB_PORT}/${KAIDI_DB_NAME}"
case "$KAIDI_DB_URL" in
"$expected_url_prefix"|"$expected_url_prefix"\?*) ;;
*) fail "Database configuration is invalid: DB_URL does not match the configured MySQL host, port, and database; application was not restarted" ;;
esac
}
status() { status() {
state=$1 state=$1
message=$2 message=$2
version=${3:-} version=${3:-}
downloaded_bytes=${4:-}
total_bytes=${5:-}
bytes_per_second=${6:-}
download_percent=${7:-}
restart_expected_seconds=${8:-}
previous_state=
previous_message=
if [ -f "$STATUS_FILE" ] && [ ! -L "$STATUS_FILE" ]; then
previous_state=$(jq -r '.state // empty' "$STATUS_FILE" 2>/dev/null || true)
previous_message=$(jq -r '.message // empty' "$STATUS_FILE" 2>/dev/null || true)
fi
tmp="$STATUS_FILE.tmp.$$" tmp="$STATUS_FILE.tmp.$$"
jq -n \ jq -n \
--arg state "$state" \ --arg state "$state" \
--arg message "$message" \ --arg message "$message" \
--arg version "$version" \ --arg version "$version" \
--arg downloadedBytes "$downloaded_bytes" \
--arg totalBytes "$total_bytes" \
--arg bytesPerSecond "$bytes_per_second" \
--arg downloadPercent "$download_percent" \
--arg restartExpectedSeconds "$restart_expected_seconds" \
--arg updatedAt "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \ --arg updatedAt "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
'{state:$state,message:$message,updatedAt:$updatedAt} '{state:$state,message:$message,updatedAt:$updatedAt}
+ (if ($version | length) > 0 then {targetVersion:$version} else {} end)' > "$tmp" + (if ($version | length) > 0 then {targetVersion:$version} else {} end)
+ (if ($downloadedBytes | test("^[0-9]+$")) then {downloadedBytes:($downloadedBytes | tonumber)} else {} end)
+ (if ($totalBytes | test("^[0-9]+$")) then {totalBytes:($totalBytes | tonumber)} else {} end)
+ (if ($bytesPerSecond | test("^[0-9]+$")) then {bytesPerSecond:($bytesPerSecond | tonumber)} else {} end)
+ (if ($downloadPercent | test("^[0-9]+$")) then {downloadPercent:($downloadPercent | tonumber)} else {} end)
+ (if ($restartExpectedSeconds | test("^[0-9]+$"))
then {restartExpectedSeconds:($restartExpectedSeconds | tonumber)} else {} end)' > "$tmp"
chmod 0644 "$tmp" chmod 0644 "$tmp"
mv -f "$tmp" "$STATUS_FILE" mv -f "$tmp" "$STATUS_FILE"
if [ "$state" != "$previous_state" ] || [ "$message" != "$previous_message" ]; then
case "$state" in
FAILED|RECOVERY_REQUIRED) event ERROR "$state" "$message" || true ;;
*) event INFO "$state" "$message" || true ;;
esac
fi
}
event() {
level=$1
stage=$2
message=$3
event_tmp="$EVENT_LOG_FILE.tmp.$$"
jq -cn --arg occurredAt "$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
--arg level "$level" --arg stage "$stage" --arg message "$message" \
'{occurredAt:$occurredAt,level:$level,stage:$stage,message:$message}' >> "$EVENT_LOG_FILE"
chmod 0644 "$EVENT_LOG_FILE"
event_size=$(wc -c < "$EVENT_LOG_FILE" | tr -d '[:space:]')
if [ "$event_size" -gt 262144 ]; then
tail -n 160 "$EVENT_LOG_FILE" > "$event_tmp"
chmod 0644 "$event_tmp"
mv -f "$event_tmp" "$EVENT_LOG_FILE"
fi
}
reset_event_log() {
rm -f "$EVENT_LOG_FILE"
touch "$EVENT_LOG_FILE"
chmod 0644 "$EVENT_LOG_FILE"
} }
archive_processing_request() { archive_processing_request() {
@@ -163,6 +237,7 @@ prepare_update_layout() {
id -nG "$SERVICE_USER" | tr ' ' '\n' | grep -Fxq "$SERVICE_GROUP" \ id -nG "$SERVICE_USER" | tr ' ' '\n' | grep -Fxq "$SERVICE_GROUP" \
|| bootstrap_die "Service user $SERVICE_USER is not a member of group $SERVICE_GROUP" || bootstrap_die "Service user $SERVICE_USER is not a member of group $SERVICE_GROUP"
command -v runuser >/dev/null 2>&1 || bootstrap_die "runuser is required" command -v runuser >/dev/null 2>&1 || bootstrap_die "runuser is required"
command -v setsid >/dev/null 2>&1 || bootstrap_die "setsid is required"
install -d -o root -g "$SERVICE_GROUP" -m 0750 \ install -d -o root -g "$SERVICE_GROUP" -m 0750 \
"$APP_ROOT" "$APP_ROOT/releases" "$APP_ROOT/runtime" "$APP_ROOT/bin" "$STATE_ROOT" \ "$APP_ROOT" "$APP_ROOT/releases" "$APP_ROOT/runtime" "$APP_ROOT/bin" "$STATE_ROOT" \
|| bootstrap_die "Managed application or update directories could not be prepared" || bootstrap_die "Managed application or update directories could not be prepared"
@@ -174,6 +249,15 @@ prepare_update_layout() {
|| bootstrap_die "Private update directories could not be prepared" || bootstrap_die "Private update directories could not be prepared"
} }
prepare_queue_layout() {
if [ -d "$PROCESSING_DIR" ] && [ ! -L "$PROCESSING_DIR" ] \
&& [ -d "$FAILED_REQUEST_ROOT" ] && [ ! -L "$FAILED_REQUEST_ROOT" ]; then
return 0
fi
install -d -o root -g root -m 0700 "$PROCESSING_DIR" "$FAILED_REQUEST_ROOT" \
|| bootstrap_die "Private update queue directories could not be prepared"
}
secure_release_tree() { secure_release_tree() {
release_dir=$1 release_dir=$1
chown -R root:"$SERVICE_GROUP" "$release_dir" || return 1 chown -R root:"$SERVICE_GROUP" "$release_dir" || return 1
@@ -197,13 +281,18 @@ verify_release_access() {
fi fi
} }
prepare_update_layout
load_runtime_database_env
# shellcheck disable=SC2329 # Invoked by the EXIT trap below. # shellcheck disable=SC2329 # Invoked by the EXIT trap below.
cleanup() { cleanup() {
rc=$? rc=$?
trap - EXIT HUP INT TERM trap - EXIT HUP INT TERM
if [ -n "$DOWNLOAD_PID" ]; then
if [ -n "$DOWNLOAD_PGID" ]; then
kill -TERM -- "-$DOWNLOAD_PGID" 2>/dev/null || true
else
kill -TERM "$DOWNLOAD_PID" 2>/dev/null || true
fi
wait "$DOWNLOAD_PID" 2>/dev/null || true
fi
[ -z "$WORK_DIR" ] || rm -rf "$WORK_DIR" [ -z "$WORK_DIR" ] || rm -rf "$WORK_DIR"
[ -z "$CACHE_TEMP" ] || rm -rf "$CACHE_TEMP" [ -z "$CACHE_TEMP" ] || rm -rf "$CACHE_TEMP"
if [ "$rc" -ne 0 ] && [ "$TERMINAL_STATUS_WRITTEN" != true ]; then if [ "$rc" -ne 0 ] && [ "$TERMINAL_STATUS_WRITTEN" != true ]; then
@@ -244,6 +333,83 @@ download() {
esac esac
} }
download_with_progress() {
progress_url=$1
progress_output=$2
progress_total=${3:-0}
progress_started=$(date +%s)
progress_previous_time=$progress_started
progress_previous_bytes=0
rm -f "$progress_output"
touch "$progress_output"
chmod 0600 "$progress_output"
case "$progress_url" in
https://*)
if [ -n "$RELEASE_TOKEN" ]; then
[ -s "$RELEASE_AUTH_HEADER_FILE" ] || return 2
setsid curl --fail --silent --show-error --proto '=https' --tlsv1.2 \
--header "@$RELEASE_AUTH_HEADER_FILE" "$progress_url" -o "$progress_output" &
else
setsid curl --fail --silent --show-error --location --proto '=https' --proto-redir '=https' \
--tlsv1.2 "$progress_url" -o "$progress_output" &
fi
;;
*)
[ "${KAIDI_ALLOW_INSECURE_UPDATE:-false}" = "true" ] || return 2
if [ -n "$RELEASE_TOKEN" ]; then
[ -s "$RELEASE_AUTH_HEADER_FILE" ] || return 2
setsid curl --fail --silent --show-error --proto '=http,https' \
--header "@$RELEASE_AUTH_HEADER_FILE" "$progress_url" -o "$progress_output" &
else
setsid curl --fail --silent --show-error --location --proto '=http,https' \
--proto-redir '=http,https' "$progress_url" -o "$progress_output" &
fi
;;
esac
DOWNLOAD_PID=$!
DOWNLOAD_PGID=$DOWNLOAD_PID
while kill -0 "$DOWNLOAD_PID" 2>/dev/null; do
progress_now=$(date +%s)
progress_bytes=$(wc -c < "$progress_output" 2>/dev/null | tr -d '[:space:]' || printf 0)
case "$progress_bytes:$progress_total" in *[!0-9:]*) progress_bytes=0; progress_total=0 ;; esac
progress_delta_seconds=$((progress_now - progress_previous_time))
[ "$progress_delta_seconds" -ge 1 ] || progress_delta_seconds=1
progress_delta_bytes=$((progress_bytes - progress_previous_bytes))
[ "$progress_delta_bytes" -ge 0 ] || progress_delta_bytes=0
progress_speed=$((progress_delta_bytes / progress_delta_seconds))
if [ "$progress_total" -gt 0 ]; then
progress_percent=$((progress_bytes * 100 / progress_total))
[ "$progress_percent" -le 99 ] || progress_percent=99
else
progress_percent=0
fi
status DOWNLOADING "Downloading signed release $TARGET_VERSION" "$TARGET_VERSION" \
"$progress_bytes" "$progress_total" "$progress_speed" "$progress_percent"
progress_previous_time=$progress_now
progress_previous_bytes=$progress_bytes
sleep 1
done
if wait "$DOWNLOAD_PID"; then
DOWNLOAD_PID=
DOWNLOAD_PGID=
else
DOWNLOAD_PID=
DOWNLOAD_PGID=
return 1
fi
progress_bytes=$(wc -c < "$progress_output" | tr -d '[:space:]')
[ "$progress_total" -gt 0 ] || progress_total=$progress_bytes
progress_finished=$(date +%s)
progress_elapsed=$((progress_finished - progress_started))
[ "$progress_elapsed" -ge 1 ] || progress_elapsed=1
progress_speed=$((progress_bytes / progress_elapsed))
LAST_DOWNLOAD_SPEED=$progress_speed
status DOWNLOADING "Release $TARGET_VERSION download completed" "$TARGET_VERSION" \
"$progress_bytes" "$progress_total" "$progress_speed" 100
}
release_asset_url() { release_asset_url() {
asset_name=$1 asset_name=$1
if [ -n "$RELEASE_API_URL" ]; then if [ -n "$RELEASE_API_URL" ]; then
@@ -275,30 +441,56 @@ EOF
wait_for_health() { wait_for_health() {
health_url=$1 health_url=$1
attempts=0 attempts=0
health_file=$(mktemp "$STATE_ROOT/work/health-response.XXXXXX")
while [ "$attempts" -lt "$HEALTH_ATTEMPTS" ]; do while [ "$attempts" -lt "$HEALTH_ATTEMPTS" ]; do
if curl -fsS "$health_url" | jq -e '.status == "UP"' >/dev/null 2>&1; then health_http=$(curl --silent --show-error --connect-timeout 2 --max-time 4 \
--output "$health_file" --write-out '%{http_code}' "$health_url" 2>/dev/null || true)
if [ "$health_http" = 200 ] && jq -e '.status == "UP"' "$health_file" >/dev/null 2>&1; then
rm -f "$health_file"
return 0 return 0
fi fi
if [ "$health_http" = 200 ]; then
SURFACE_FAILURE=HEALTH_DOWN
elif [ -n "$health_http" ] && [ "$health_http" != 000 ]; then
SURFACE_FAILURE="HEALTH_HTTP_$health_http"
else
SURFACE_FAILURE=HEALTH_UNREACHABLE
fi
attempts=$((attempts + 1)) attempts=$((attempts + 1))
sleep "$HEALTH_INTERVAL_SECONDS" sleep "$HEALTH_INTERVAL_SECONDS"
done done
rm -f "$health_file"
return 1 return 1
} }
verify_app_surface() { verify_app_surface() {
expected_release=${1:-} expected_release=${1:-}
SURFACE_FAILURE=
wait_for_health "$HEALTH_URL" || return 1 wait_for_health "$HEALTH_URL" || return 1
index_file=$(mktemp "$STATE_ROOT/work/public-index.XXXXXX") index_file=$(mktemp "$STATE_ROOT/work/public-index.XXXXXX")
if curl -fsS "$APP_INDEX_URL" -o "$index_file" \ index_http=$(curl --silent --show-error --connect-timeout 2 --max-time 5 \
--output "$index_file" --write-out '%{http_code}' "$APP_INDEX_URL" 2>/dev/null || true)
if [ "$index_http" = 200 ] \
&& grep -Eiq '<!doctype|<html' "$index_file"; then && grep -Eiq '<!doctype|<html' "$index_file"; then
rm -f "$index_file" rm -f "$index_file"
if [ "$PROCESS_MANAGER" = baota ] && [ -n "$expected_release" ]; then if [ "$PROCESS_MANAGER" = baota ] && [ -n "$expected_release" ]; then
running_release=$(baota_process_release) || return 1 running_release=$(baota_process_release) || {
[ "$running_release" = "$expected_release" ] || return 1 SURFACE_FAILURE=PROCESS_IDENTITY_INVALID
return 1
}
if [ "$running_release" != "$expected_release" ]; then
SURFACE_FAILURE=RELEASE_MISMATCH
return 1
fi
fi fi
return 0 return 0
fi fi
rm -f "$index_file" rm -f "$index_file"
if [ "$index_http" != 200 ]; then
SURFACE_FAILURE="INDEX_HTTP_${index_http:-000}"
else
SURFACE_FAILURE=INDEX_CONTENT_INVALID
fi
return 1 return 1
} }
@@ -545,6 +737,15 @@ remove_failed_release() {
esac esac
} }
quarantine_active_transaction() {
[ -d "$ACTIVE_TRANSACTION" ] || return 0
recovery_transaction="$TRANSACTION_ROOT/recovery-required"
if [ -e "$recovery_transaction" ] || [ -L "$recovery_transaction" ]; then
recovery_transaction="$TRANSACTION_ROOT/recovery-required-$(date -u +%Y%m%dT%H%M%SZ)-$$"
fi
mv "$ACTIVE_TRANSACTION" "$recovery_transaction"
}
rollback_active_transaction() { rollback_active_transaction() {
reason=$1 reason=$1
previous_target=$(transaction_value previous-target) previous_target=$(transaction_value previous-target)
@@ -574,10 +775,19 @@ rollback_active_transaction() {
fail "$reason; previous application release is running, but operations restoration requires manual review; transaction evidence was retained" fail "$reason; previous application release is running, but operations restoration requires manual review; transaction evidence was retained"
fi fi
TERMINAL_STATUS_WRITTEN=true TERMINAL_STATUS_WRITTEN=true
status FAILED "$reason; rollback is incomplete and manual recovery is required" "${TARGET_VERSION:-}" recovery_guard_failed=false
if ! archive_processing_request; then if ! archive_processing_request; then
printf '%s\n' "Update request could not be archived after an incomplete rollback" >&2 printf '%s\n' "Update request could not be archived after an incomplete rollback" >&2
recovery_guard_failed=true
fi fi
if ! quarantine_active_transaction; then
printf '%s\n' "Update transaction evidence could not be quarantined after an incomplete rollback" >&2
recovery_guard_failed=true
fi
if [ "$recovery_guard_failed" = true ]; then
systemctl stop "$UPDATE_PATH_NAME" >/dev/null 2>&1 || true
fi
status RECOVERY_REQUIRED "$reason; rollback is incomplete and manual recovery is required" "${TARGET_VERSION:-}"
printf '%s\n' "$reason; rollback is incomplete and manual recovery is required" >&2 printf '%s\n' "$reason; rollback is incomplete and manual recovery is required" >&2
exit 1 exit 1
} }
@@ -616,6 +826,7 @@ validate_release_operations() {
"$WORK_DIR/extracted/ops/kaidi-update.path" >/dev/null || return 1 "$WORK_DIR/extracted/ops/kaidi-update.path" >/dev/null || return 1
} }
prepare_queue_layout
exec 9>"$LOCK_FILE" exec 9>"$LOCK_FILE"
flock -n 9 || exit 0 flock -n 9 || exit 0
recover_interrupted_transaction recover_interrupted_transaction
@@ -641,6 +852,16 @@ else
fi fi
chmod 0600 "$PROCESSING_FILE" chmod 0600 "$PROCESSING_FILE"
if [ -f "$STATUS_FILE" ] && [ ! -L "$STATUS_FILE" ] \
&& jq -e '.state == "RECOVERY_REQUIRED"' "$STATUS_FILE" >/dev/null 2>&1; then
TERMINAL_STATUS_WRITTEN=true
if ! archive_processing_request; then
systemctl stop "$UPDATE_PATH_NAME" >/dev/null 2>&1 || true
fi
printf '%s\n' "Update service is locked for manual recovery; new requests are rejected" >&2
exit 1
fi
if ! REQUESTED_VERSION=$(jq -er '.version | strings | select(length > 0 and length <= 128)' \ if ! REQUESTED_VERSION=$(jq -er '.version | strings | select(length > 0 and length <= 128)' \
"$PROCESSING_FILE"); then "$PROCESSING_FILE"); then
fail "Update request version is invalid" fail "Update request version is invalid"
@@ -650,6 +871,12 @@ TARGET_VERSION=$REQUESTED_VERSION
REQUEST_ACTION=$(jq -er '(.action // "INSTALL") | strings | ascii_upcase REQUEST_ACTION=$(jq -er '(.action // "INSTALL") | strings | ascii_upcase
| select(. == "DOWNLOAD" or . == "INSTALL")' "$PROCESSING_FILE") \ | select(. == "DOWNLOAD" or . == "INSTALL")' "$PROCESSING_FILE") \
|| fail "Update request action is invalid" || fail "Update request action is invalid"
prepare_update_layout
reset_event_log
load_runtime_database_env
if [ "$REQUEST_ACTION" = INSTALL ]; then
validate_runtime_database_config
fi
[ -z "$RELEASE_TOKEN" ] || { [ "${#RELEASE_TOKEN}" -le 512 ] \ [ -z "$RELEASE_TOKEN" ] || { [ "${#RELEASE_TOKEN}" -le 512 ] \
&& ! printf '%s' "$RELEASE_TOKEN" | grep -q '[[:cntrl:]]'; } \ && ! printf '%s' "$RELEASE_TOKEN" | grep -q '[[:cntrl:]]'; } \
|| fail "UPDATE_RELEASE_TOKEN is invalid" || fail "UPDATE_RELEASE_TOKEN is invalid"
@@ -702,6 +929,8 @@ ARTIFACT=$(jq -er '.artifact | strings | select(test("^[A-Za-z0-9][A-Za-z0-9._+-
"$WORK_DIR/release-manifest.json") || fail "Release artifact name is invalid" "$WORK_DIR/release-manifest.json") || fail "Release artifact name is invalid"
EXPECTED_SHA=$(jq -er '.sha256 | strings | ascii_downcase | select(test("^[0-9a-f]{64}$"))' \ EXPECTED_SHA=$(jq -er '.sha256 | strings | ascii_downcase | select(test("^[0-9a-f]{64}$"))' \
"$WORK_DIR/release-manifest.json") || fail "Release SHA-256 is invalid" "$WORK_DIR/release-manifest.json") || fail "Release SHA-256 is invalid"
EXPECTED_SIZE=$(jq -er '(.artifactSizeBytes // 0) | numbers | floor | select(. >= 0)' \
"$WORK_DIR/release-manifest.json") || fail "Release artifact size is invalid"
CURRENT_VERSION=$(cat "$APP_ROOT/current/VERSION" 2>/dev/null || true) CURRENT_VERSION=$(cat "$APP_ROOT/current/VERSION" 2>/dev/null || true)
if [ "$CURRENT_VERSION" = "$TARGET_VERSION" ]; then if [ "$CURRENT_VERSION" = "$TARGET_VERSION" ]; then
@@ -714,12 +943,16 @@ fi
if [ "$REQUEST_ACTION" = DOWNLOAD ]; then if [ "$REQUEST_ACTION" = DOWNLOAD ]; then
status DOWNLOADING "Downloading signed release $TARGET_VERSION" "$TARGET_VERSION" status DOWNLOADING "Downloading signed release $TARGET_VERSION" "$TARGET_VERSION"
ARTIFACT_URL=$(release_asset_url "$ARTIFACT") || fail "Release artifact asset is missing" ARTIFACT_URL=$(release_asset_url "$ARTIFACT") || fail "Release artifact asset is missing"
download "$ARTIFACT_URL" "$WORK_DIR/release.tar.gz" || fail "Release artifact download failed" download_with_progress "$ARTIFACT_URL" "$WORK_DIR/release.tar.gz" "$EXPECTED_SIZE" \
|| fail "Release artifact download failed"
else else
status VERIFYING "Revalidating cached release $TARGET_VERSION" "$TARGET_VERSION" status VERIFYING "Revalidating cached release $TARGET_VERSION" "$TARGET_VERSION"
fi fi
ACTUAL_SHA=$(sha256sum "$WORK_DIR/release.tar.gz" | awk '{print $1}') ACTUAL_SHA=$(sha256sum "$WORK_DIR/release.tar.gz" | awk '{print $1}')
[ "$ACTUAL_SHA" = "$EXPECTED_SHA" ] || fail "Release artifact SHA-256 verification failed" [ "$ACTUAL_SHA" = "$EXPECTED_SHA" ] || fail "Release artifact SHA-256 verification failed"
ACTUAL_SIZE=$(wc -c < "$WORK_DIR/release.tar.gz" | tr -d '[:space:]')
[ "$EXPECTED_SIZE" -eq 0 ] || [ "$ACTUAL_SIZE" -eq "$EXPECTED_SIZE" ] \
|| fail "Release artifact size verification failed"
tar -tzf "$WORK_DIR/release.tar.gz" > "$WORK_DIR/archive.list" || fail "Release archive could not be listed" tar -tzf "$WORK_DIR/release.tar.gz" > "$WORK_DIR/archive.list" || fail "Release archive could not be listed"
if grep -Eq '(^/|(^|/)\.\.(/|$))' "$WORK_DIR/archive.list"; then if grep -Eq '(^/|(^|/)\.\.(/|$))' "$WORK_DIR/archive.list"; then
@@ -756,7 +989,8 @@ if [ "$REQUEST_ACTION" = DOWNLOAD ]; then
fi fi
mv "$CACHE_TEMP" "$CACHE_DIR" || fail "Verified release cache could not be activated" mv "$CACHE_TEMP" "$CACHE_DIR" || fail "Verified release cache could not be activated"
CACHE_TEMP= CACHE_TEMP=
status READY "Release $TARGET_VERSION is downloaded and verified; confirm installation" "$TARGET_VERSION" status READY "Release $TARGET_VERSION is downloaded and verified; confirm installation" "$TARGET_VERSION" \
"$ACTUAL_SIZE" "$ACTUAL_SIZE" "$LAST_DOWNLOAD_SPEED" 100
TERMINAL_STATUS_WRITTEN=true TERMINAL_STATUS_WRITTEN=true
complete_request complete_request
exit 0 exit 0
@@ -779,6 +1013,13 @@ if ! verify_release_access "$RELEASE_DIR"; then
fi fi
PREVIOUS_TARGET=$(readlink "$APP_ROOT/current" 2>/dev/null || true) PREVIOUS_TARGET=$(readlink "$APP_ROOT/current" 2>/dev/null || true)
status PRECHECKING "Validating current release before switching to $TARGET_VERSION" "$TARGET_VERSION"
if [ -z "$PREVIOUS_TARGET" ] || [ ! -d "$PREVIOUS_TARGET" ]; then
fail "Current release path is invalid; application was not restarted"
fi
if ! verify_app_surface "$PREVIOUS_TARGET"; then
fail "Current release preflight failed (${SURFACE_FAILURE:-UNKNOWN}); application was not restarted"
fi
mkdir "$ACTIVE_TRANSACTION" mkdir "$ACTIVE_TRANSACTION"
write_transaction_value target-version "$TARGET_VERSION" write_transaction_value target-version "$TARGET_VERSION"
write_transaction_value previous-target "$PREVIOUS_TARGET" write_transaction_value previous-target "$PREVIOUS_TARGET"
@@ -805,7 +1046,7 @@ if ! ln -sfn "$RELEASE_DIR" "$APP_ROOT/current.next" \
fi fi
write_transaction_value phase APP_SWITCHED write_transaction_value phase APP_SWITCHED
status RUNNING "Starting and verifying release $TARGET_VERSION" "$TARGET_VERSION" status RUNNING "Starting and verifying release $TARGET_VERSION" "$TARGET_VERSION" "" "" "" "" 10
write_transaction_value phase HEALTH_CHECKING write_transaction_value phase HEALTH_CHECKING
if ! restart_application; then if ! restart_application; then
rollback_active_transaction "Release application restart failed" rollback_active_transaction "Release application restart failed"
@@ -825,5 +1066,6 @@ fi
service_state=$(application_state 2>/dev/null || true) service_state=$(application_state 2>/dev/null || true)
[ -n "$service_state" ] || service_state=unknown [ -n "$service_state" ] || service_state=unknown
surface_failure=${SURFACE_FAILURE:-UNKNOWN}
rollback_active_transaction \ rollback_active_transaction \
"Release health or application-surface verification failed (service state: $service_state)" "Release application verification failed ($surface_failure; service state: $service_state)"
+9 -9
View File
@@ -76,7 +76,7 @@
| 第一版 Preview | PAGE-01~22 页面和菜单框架齐备,真实前后端核心链保持可用;Preview 上线与整套 R1 最终验收分开计量 | | 第一版 Preview | PAGE-01~22 页面和菜单框架齐备,真实前后端核心链保持可用;Preview 上线与整套 R1 最终验收分开计量 |
| 来源表格校验 | V068 为 14 类 OA 的 33 个 TABLE 字段补齐嵌套类型、必填和文件引用规则;V069 保留 OA-02 v1 历史账户表格契约,避免 v2 字段追溯污染 | | 来源表格校验 | V068 为 14 类 OA 的 33 个 TABLE 字段补齐嵌套类型、必填和文件引用规则;V069 保留 OA-02 v1 历史账户表格契约,避免 v2 字段追溯污染 |
| PAGE-20 审计 | 增加不可变事件序号、四种稳定排序、URL 查询状态、同排序 CSV 导出、脱敏详情及 OpenAPI `422` 参数门禁 | | PAGE-20 审计 | 增加不可变事件序号、四种稳定排序、URL 查询状态、同排序 CSV 导出、脱敏详情及 OpenAPI `422` 参数门禁 |
| PAGE-22 在线更新 | 更新源固定为公共 Gitea Latest Release API,默认不使用 Token;系统管理员点击“获取更新”后自动检查并下载,验签缓存进入 `READY` 后显示“立即重启”。安装健康检查成功后页面从 10 秒倒计时自动刷新;刷新或短暂断线发生在安装中时恢复轮询。后台只写固定结构请求,由 root oneshot 服务验签、验哈希、备份、切换和回滚,不接受页面传入地址、Token 或命令 | | PAGE-22 在线更新 | 更新源固定为公共 Gitea Latest Release API,默认不使用 Token;“获取版本”只读取最新版本信息,发现新版本后由管理员点击“立即更新”开始下载。下载、验签完成进入 `READY/下载完成` 后显示“立即更新并重启”。安装健康检查成功后页面从 10 秒倒计时自动刷新;刷新、短暂断线或命令响应丢失时恢复状态轮询。后台只写固定结构请求,由 root oneshot 服务验签、验哈希、备份、切换和回滚,不接受页面传入地址、Token 或命令 |
| Release 工程 | `.gitea/workflows/release.yml` 监听严格 SemVer `v*` tag;Maven `revision`、npm、JAR、前后端 SBOM、签名 manifest 与 tag 必须同版本。工作流执行 Java/前端/OpenAPI/Playwright/依赖审计,使用至少 3072 位 RSA 密钥生成并独立验收恰好 9 个资产;先创建不可见草稿、逐项上传并核对名称/大小,最后发布为可被 `/releases/latest` 读取的正式 Release | | Release 工程 | `.gitea/workflows/release.yml` 监听严格 SemVer `v*` tag;Maven `revision`、npm、JAR、前后端 SBOM、签名 manifest 与 tag 必须同版本。工作流执行 Java/前端/OpenAPI/Playwright/依赖审计,使用至少 3072 位 RSA 密钥生成并独立验收恰好 9 个资产;先创建不可见草稿、逐项上传并核对名称/大小,最后发布为可被 `/releases/latest` 读取的正式 Release |
| Linux 32 位 | i386/i486/i586/i686 下载 Java 17 i686 JRE;JRE 元数据和归档均使用仅允许 HTTPS/TLS 1.2 及以上的受限下载器;由于 MySQL 8.4 无对应服务端镜像,要求预置外部 MySQL 8.4.x,curl 安装只开启 `/setup` 向导,数据库密码在浏览器中提交并完成连接、版本及 DDL/DML 预检 | | Linux 32 位 | i386/i486/i586/i686 下载 Java 17 i686 JRE;JRE 元数据和归档均使用仅允许 HTTPS/TLS 1.2 及以上的受限下载器;由于 MySQL 8.4 无对应服务端镜像,要求预置外部 MySQL 8.4.x,curl 安装只开启 `/setup` 向导,数据库密码在浏览器中提交并完成连接、版本及 DDL/DML 预检 |
| 更新可靠性 | 下载和安装拆为两个持久动作;下载阶段不停止业务服务,安装阶段只接受同版本 `READY` 缓存并重新验签。公共 Gitea 默认不使用 Token;如改接私有镜像,Token 仅从权限为 `0600` 的 root 配置/临时文件读取,不进入 `curl` 参数、页面、状态或日志,且只允许同源 API/资产使用;请求原子领取到持久 `processing`,systemd 限制失败重试;`mysqldump`、新旧版本健康和回滚均有独立门禁,跨来源拒绝、成功、健康回滚、下载失败、备份失败和不安全请求夹具纳入 CI | | 更新可靠性 | 下载和安装拆为两个持久动作;下载阶段不停止业务服务,安装阶段只接受同版本 `READY` 缓存并重新验签。公共 Gitea 默认不使用 Token;如改接私有镜像,Token 仅从权限为 `0600` 的 root 配置/临时文件读取,不进入 `curl` 参数、页面、状态或日志,且只允许同源 API/资产使用;请求原子领取到持久 `processing`,systemd 限制失败重试;`mysqldump`、新旧版本健康和回滚均有独立门禁,跨来源拒绝、成功、健康回滚、下载失败、备份失败和不安全请求夹具纳入 CI |
@@ -695,7 +695,7 @@ OA 导入路线不重新判断原 OA 的业务审批结论,但财务金额、
| PAGE-19 | 查询与报表页 | 三类角色按权限 | 项目台账、合同、收付款、流程、附件完整性和导出 | | PAGE-19 | 查询与报表页 | 三类角色按权限 | 项目台账、合同、收付款、流程、附件完整性和导出 |
| PAGE-20 | 审计日志页 | 审计/授权管理员 | 查询登录、查看、修改、审批、导入、导出和结果登记记录 | | PAGE-20 | 审计日志页 | 审计/授权管理员 | 查询登录、查看、修改、审批、导入、导出和结果登记记录 |
| PAGE-21 | 权限与配置页 | 系统管理员 | 用户、角色、数据范围、模板和参数版本 | | PAGE-21 | 权限与配置页 | 系统管理员 | 用户、角色、数据范围、模板和参数版本 |
| PAGE-22 | 系统更新页 | 系统管理员 | 当前/最新版本、更新包获取、立即重启和历史更新记录 | | PAGE-22 | 系统更新页 | 系统管理员 | 当前/最新版本、显式下载、下载完成确认、安装重启和历史更新记录 |
### 8.2 PAGE-01 登录页 ### 8.2 PAGE-01 登录页
@@ -1002,9 +1002,9 @@ PAGE-21 只向超级管理员开放。超级管理员账号不得混授普通业
### 8.22.1 PAGE-22 系统更新页 ### 8.22.1 PAGE-22 系统更新页
系统更新使用独立入口 `/governance/update`,同时显示当前版本、最新版本、更新状态、四步进度和最近更新记录。拥有 `admin:update:view` 的隔离系统管理员可进入页面;下载与重启安装仍由 `admin:update:execute` 和服务端 `allowedActions` 共同控制。未启用或 Release 地址无效时显示明确禁用状态并禁用“获取更新”。 系统更新使用独立入口 `/governance/update`,同时显示当前版本、最新版本、更新状态、四步进度和最近更新记录。拥有 `admin:update:view` 的隔离系统管理员可进入页面;下载与重启安装仍由 `admin:update:execute` 和服务端 `allowedActions` 共同控制。未启用或 Release 地址无效时显示明确禁用状态并禁用“获取版本”。
更新固定分两阶段。管理员点击“获取更新”后,前端先检查最新版本,再自动提交 `DOWNLOAD` 请求;root oneshot 从固定 Gitea Latest Release API 下载 manifest、签名和应用包,验签/验哈希后写入 root-only 版本缓存并进入 `READY`,期间当前业务版本继续运行。进入 `READY` 后页面显示“立即重启”,点击后只允许安装同版本缓存,并在切换前重新验证。健康检查成功后页面显示 10 秒倒计时并自动刷新;若页面在 `INSTALL_QUEUED/BACKING_UP/INSTALLING/RUNNING` 时刷新或短暂断线,重新进入后自动恢复 3 秒轮询。失败时保留明确状态并恢复已验证的上一版本。 更新固定为“检查、下载、安装”三个服务端阶段和四个明确用户反馈。管理员点击“获取版本”时只请求最新版本、发布时间和发布说明,不提交下载;发现新版本后显示“立即更新”,再次确认后才提交 `DOWNLOAD`。root oneshot 从固定 Gitea Latest Release API 下载 manifest、签名和应用包,验签/验哈希后写入 root-only 版本缓存并进入 `READY/下载完成`,期间当前业务版本继续运行。此时页面显示“立即更新并重启”,点击后只允许安装同版本缓存,并在切换前重新验证。页面以 3 秒轮询显示排队、下载、校验、备份、安装和重启状态;命令已经被服务端接受但 HTTP 响应丢失时也会主动重读状态。健康检查成功后显示 10 秒倒计时并自动刷新;失败时保留明确状态并恢复已验证的上一版本。
页面只提交目标版本和原因,不接收下载地址、Token、脚本或任意命令。公共 Gitea 默认不配置 Token;如改接私有镜像,只读 Token 仅存在于权限为 `0600` 的 root 环境文件和临时 Header 文件,不进入进程参数、DTO、状态 JSON、审计参数或页面响应;API 和资产必须同 scheme、host、port,认证请求不跟随跨来源重定向。文件锁和 inbox/processing 双路径防止并发覆盖,独立 root oneshot 执行 RSA/SHA-256 校验、可验证数据库备份、持久事务、应用与运维文件原子切换、新旧版本健康检查和失败回滚。 页面只提交目标版本和原因,不接收下载地址、Token、脚本或任意命令。公共 Gitea 默认不配置 Token;如改接私有镜像,只读 Token 仅存在于权限为 `0600` 的 root 环境文件和临时 Header 文件,不进入进程参数、DTO、状态 JSON、审计参数或页面响应;API 和资产必须同 scheme、host、port,认证请求不跟随跨来源重定向。文件锁和 inbox/processing 双路径防止并发覆盖,独立 root oneshot 执行 RSA/SHA-256 校验、可验证数据库备份、持久事务、应用与运维文件原子切换、新旧版本健康检查和失败回滚。
@@ -1045,7 +1045,7 @@ PAGE-21 只向超级管理员开放。超级管理员账号不得混授普通业
| PAGE-19 查询报表 | `pages/reports` | `Tabs`、`Form`、`Table`、按需 `ECharts` | `/api/v1/reports/{reportCode}`、`drilldown`、`exports` | 六类报表同口径汇总、下钻、导出;不以硬编码数字或前端合计冒充结果 | | PAGE-19 查询报表 | `pages/reports` | `Tabs`、`Form`、`Table`、按需 `ECharts` | `/api/v1/reports/{reportCode}`、`drilldown`、`exports` | 六类报表同口径汇总、下钻、导出;不以硬编码数字或前端合计冒充结果 |
| PAGE-20 审计日志 | `pages/governance/audit` | `Form`、`Table`、`Drawer`、`Tag` | `/api/v1/audit/logs`、`/api/v1/audit/exports` | 授权审计人员按请求编号还原关键动作;日志不可由业务页面修改/删除 | | PAGE-20 审计日志 | `pages/governance/audit` | `Form`、`Table`、`Drawer`、`Tag` | `/api/v1/audit/logs`、`/api/v1/audit/exports` | 授权审计人员按请求编号还原关键动作;日志不可由业务页面修改/删除 |
| PAGE-21 权限与配置 | `pages/governance/settings` | `Tabs`、`Tree`、`Table`、`Form`、`Dialog` | `/api/v1/admin/users`、`roles`、`scopes`、`templates`、`parameters` | 仅超级管理员可用;用户、角色、范围、模板和参数按版本与动作白名单管理 | | PAGE-21 权限与配置 | `pages/governance/settings` | `Tabs`、`Tree`、`Table`、`Form`、`Dialog` | `/api/v1/admin/users`、`roles`、`scopes`、`templates`、`parameters` | 仅超级管理员可用;用户、角色、范围、模板和参数按版本与动作白名单管理 |
| PAGE-22 系统更新 | `pages/governance/update` | `Steps`、`Table`、`Alert`、`Tag`、`Button` | `/api/v1/admin/system-update/{check,download,install}`、`/api/v1/audit/logs` | 获取更新自动完成检查和下载;验签完成后显示立即重启;健康后 10 秒刷新;历史操作来自不可变审计日志 | | PAGE-22 系统更新 | `pages/governance/update` | `Steps`、`Table`、`Alert`、`Tag`、`Button` | `/api/v1/admin/system-update/{check,download,install}`、`/api/v1/audit/logs` | 获取版本只检查;立即更新才下载;下载完成后显示立即更新并重启;健康后 10 秒刷新;历史操作来自不可变审计日志 |
每个页面只有同时满足以下条件才算完成: 每个页面只有同时满足以下条件才算完成:
@@ -1083,7 +1083,7 @@ PAGE-21 只向超级管理员开放。超级管理员账号不得混授普通业
| PAGE-19 | 默认项目综合台账和当前月份/授权范围 | 筛选 → 汇总 → 点击金额下钻 → 导出 | 汇总、明细和导出同一口径;每个数字可到来源对象 | | PAGE-19 | 默认项目综合台账和当前月份/授权范围 | 筛选 → 汇总 → 点击金额下钻 → 导出 | 汇总、明细和导出同一口径;每个数字可到来源对象 |
| PAGE-20 | 默认最近 24 小时授权范围内审计记录 | 按用户/对象/动作/请求编号查询 → 查看前后值或导出 | 可用请求编号还原完整动作链;前后值按敏感规则脱敏 | | PAGE-20 | 默认最近 24 小时授权范围内审计记录 | 按用户/对象/动作/请求编号查询 → 查看前后值或导出 | 可用请求编号还原完整动作链;前后值按敏感规则脱敏 |
| PAGE-21 | 默认用户管理页签,只向系统管理员开放 | 编辑草稿 → 校验冲突 → 保存/发布新配置版本 | 新版本有生效时间和发布人;权限变更使受影响旧会话立即失效 | | PAGE-21 | 默认用户管理页签,只向系统管理员开放 | 编辑草稿 → 校验冲突 → 保存/发布新配置版本 | 新版本有生效时间和发布人;权限变更使受影响旧会话立即失效 |
| PAGE-22 | 当前版本、最新版本、更新状态和最近更新记录 | 获取更新 → 自动下载验签 → 立即重启 → 等待健康检查 | 健康检查成功后倒计时 10 秒自动刷新;失败状态和审计历史可查询 | | PAGE-22 | 当前版本、最新版本、更新状态和最近更新记录 | 获取版本 → 立即更新并下载验签 → 下载完成 → 立即更新并重启 → 等待健康检查 | 健康检查成功后倒计时 10 秒自动刷新;失败状态和审计历史可查询 |
所有列表默认每页 20 条;默认排序已在上表写明,未单独写明时使用 `updatedAt,desc`。无功能权限的动作隐藏;有功能权限但当前状态、资料或岗位互斥不允许的动作禁用并说明原因。任何写操作成功后都必须重新读取服务端对象和允许动作,不能只修改前端状态;失败时保留尚未提交成功的用户输入。 所有列表默认每页 20 条;默认排序已在上表写明,未单独写明时使用 `updatedAt,desc`。无功能权限的动作隐藏;有功能权限但当前状态、资料或岗位互斥不允许的动作禁用并说明原因。任何写操作成功后都必须重新读取服务端对象和允许动作,不能只修改前端状态;失败时保留尚未提交成功的用户输入。
@@ -1109,7 +1109,7 @@ PAGE-21 只向超级管理员开放。超级管理员账号不得混授普通业
| PAGE-19 查询与报表 | `reportCode` 加该报表冻结的公司/项目/对象/状态/日期条件;默认当前月 | 每个报表只开放其列代码,最终补业务编号 | 六类报表列以 D-08 为准;汇总、下钻、导出必须使用同一 filter hash 和口径版本 | | PAGE-19 查询与报表 | `reportCode` 加该报表冻结的公司/项目/对象/状态/日期条件;默认当前月 | 每个报表只开放其列代码,最终补业务编号 | 六类报表列以 D-08 为准;汇总、下钻、导出必须使用同一 filter hash 和口径版本 |
| PAGE-20 审计日志 | `occurredFrom/To`(默认近 24 小时)、`actorId`、`identityCode`、`objectType`、`objectId`、`action`、`requestId`、`result` | `occurredAt`(默认倒序)、`eventSequence` | 时间、用户、身份、范围摘要、对象、动作、结果、原因、请求编号;查看脱敏前后值、导出;没有修改/删除 | | PAGE-20 审计日志 | `occurredFrom/To`(默认近 24 小时)、`actorId`、`identityCode`、`objectType`、`objectId`、`action`、`requestId`、`result` | `occurredAt`(默认倒序)、`eventSequence` | 时间、用户、身份、范围摘要、对象、动作、结果、原因、请求编号;查看脱敏前后值、导出;没有修改/删除 |
| PAGE-21 权限与配置 | `resource`、`keyword`、`status`、`versionStatus`、`effectiveDate` | `name/code/status/updatedAt/effectiveAt` | 用户/角色/范围/模板/参数的代码、名称、版本、状态、生效时间、发布人;新增、编辑、启停、发布,按资源动作白名单执行 | | PAGE-21 权限与配置 | `resource`、`keyword`、`status`、`versionStatus`、`effectiveDate` | `name/code/status/updatedAt/effectiveAt` | 用户/角色/范围/模板/参数的代码、名称、版本、状态、生效时间、发布人;新增、编辑、启停、发布,按资源动作白名单执行 |
| PAGE-22 系统更新 | 固定读取当前状态与 `objectType=SYSTEM_UPDATE` 历史 | 历史按 `occurredAt,desc` | 当前/最新版本、状态、发布说明、操作时间、目标版本、动作、操作人和结果;获取更新、立即重启 | | PAGE-22 系统更新 | 固定读取当前状态与 `objectType=SYSTEM_UPDATE` 历史 | 历史按 `occurredAt,desc` | 当前/最新版本、状态、发布说明、操作时间、目标版本、动作、操作人和结果;获取版本、立即更新、立即更新并重启 |
列代码、筛选参数、排序字段和导出字段在 OpenAPI 中逐项枚举,前端不得把任意对象属性透传为查询字段。金额汇总由后端在同一筛选下返回,前端只格式化显示;当前页合计与全量合计必须使用不同标签。每个工作台快捷入口都要有 Playwright 断言,证明目标路由、初始筛选、返回恢复和数据数量一致。 列代码、筛选参数、排序字段和导出字段在 OpenAPI 中逐项枚举,前端不得把任意对象属性透传为查询字段。金额汇总由后端在同一筛选下返回,前端只格式化显示;当前页合计与全量合计必须使用不同标签。每个工作台快捷入口都要有 Playwright 断言,证明目标路由、初始筛选、返回恢复和数据数量一致。
@@ -1648,7 +1648,7 @@ PAGE-01~PAGE-22 必须从以下模板组合,不允许每个开发人员各
| 录入/导入 | PAGE-10、PAGE-12 的编辑状态 | 分组表单 + 动态明细 + 附件 + 校验结果 + 底部固定操作栏 | `Form`、`Row`、`Col`、`Input`/`MoneyInput`、仅整数 `InputNumber`、`Select`、`DatePicker`、`Upload`、`Alert` | | 录入/导入 | PAGE-10、PAGE-12 的编辑状态 | 分组表单 + 动态明细 + 附件 + 校验结果 + 底部固定操作栏 | `Form`、`Row`、`Col`、`Input`/`MoneyInput`、仅整数 `InputNumber`、`Select`、`DatePicker`、`Upload`、`Alert` |
| 审批处理 | PAGE-11、PAGE-17 | 待办列表 + 业务摘要 + 附件/校验 + 审批时间线 + 当前节点动作 | `Table`、`Descriptions`、`Steps`、`Timeline`、`Dialog`、`Textarea` | | 审批处理 | PAGE-11、PAGE-17 | 待办列表 + 业务摘要 + 附件/校验 + 审批时间线 + 当前节点动作 | `Table`、`Descriptions`、`Steps`、`Timeline`、`Dialog`、`Textarea` |
| 配置管理 | PAGE-21 | 配置分类 + 版本化列表/详情 + 新增编辑弹窗;生效操作和业务操作分离 | `Tabs`、`Tree`、`Table`、`Form`、`Dialog`、`Popconfirm` | | 配置管理 | PAGE-21 | 配置分类 + 版本化列表/详情 + 新增编辑弹窗;生效操作和业务操作分离 | `Tabs`、`Tree`、`Table`、`Form`、`Dialog`、`Popconfirm` |
| 系统更新 | PAGE-22 | 版本摘要 + 获取/下载进度 + 立即重启 + 审计历史 | `Steps`、`Table`、`Alert`、`Tag`、`Button` | | 系统更新 | PAGE-22 | 版本摘要 + 独立检查 + 下载进度/完成确认 + 安装重启 + 审计历史 | `Steps`、`Table`、`Alert`、`Tag`、`Button` |
| 结果/异常 | 全部页面 | 明确状态、可理解原因、请求编号和下一步动作 | `Result`、`Empty`、`Alert`、`Button`、`Skeleton` | | 结果/异常 | 全部页面 | 明确状态、可理解原因、请求编号和下一步动作 | `Result`、`Empty`、`Alert`、`Button`、`Skeleton` |
工作台不是营销首页,不使用大幅 Hero、插画横幅或仅作装饰的图表。图表必须回答一个业务问题,并提供同口径数字和可下钻明细;无有效业务含义时使用表格。 工作台不是营销首页,不使用大幅 Hero、插画横幅或仅作装饰的图表。图表必须回答一个业务问题,并提供同口径数字和可下钻明细;无有效业务含义时使用表格。
@@ -2932,7 +2932,7 @@ PAGE-16 全类回归曾暴露测试证据文件路径硬编码与应用 `finance
| 检查项 | 本轮结果 | 证据边界 | | 检查项 | 本轮结果 | 证据边界 |
| --- | --- | --- | | --- | --- | --- |
| 固定更新源 | Git remote 已绑定 `https://git.awaioi.com/ERP-Team/kaidi.git`;生产读取 `https://git.awaioi.com/api/v1/repos/ERP-Team/kaidi/releases/latest`,资产 URL 必须与 API 的 scheme、host、port 完全同源 | 页面不能修改更新地址、Token、脚本或命令;生产只读 Token 与 Gitea Actions 发布权限分离 | | 固定更新源 | Git remote 已绑定 `https://git.awaioi.com/ERP-Team/kaidi.git`;生产读取 `https://git.awaioi.com/api/v1/repos/ERP-Team/kaidi/releases/latest`,资产 URL 必须与 API 的 scheme、host、port 完全同源 | 页面不能修改更新地址、Token、脚本或命令;生产只读 Token 与 Gitea Actions 发布权限分离 |
| 两阶段交互 | 管理员点击“获取更新”后自动完成检查和下载;下载、RSA 验签、SHA-256 和压缩包检查完成后进入 `READY`,业务服务在下载阶段不停机;只有 `READY` 状态才能显示“立即重启”并提交安装 | 检查、下载、安装的忙碌状态互斥,防止重复排队;未经“立即重启”确认不切换版本 | | 分阶段交互 | 管理员点击“获取版本”只检查发布信息;发现新版本后点击“立即更新”才下载。下载、RSA 验签、SHA-256 和压缩包检查完成后进入 `READY/下载完成`,业务服务在下载阶段不停机;只有 `READY` 状态才能显示“立即更新并重启”并提交安装 | 检查、下载、安装的忙碌状态互斥,防止重复排队;未经“立即更新并重启”确认不切换版本 |
| 安装与页面恢复 | 安装阶段重新验签、备份、原子切换并执行后端直连、Nginx、更新 path unit 和静态首页健康检查;成功后页面倒计时 10 秒自动刷新,安装中刷新或短暂断线会恢复 3 秒轮询;失败自动恢复并复验上一版本 | 10 秒是页面刷新等待,不延迟服务端安装;真实 Linux systemd 主机仍须执行发布后冒烟和备份恢复演练 | | 安装与页面恢复 | 安装阶段重新验签、备份、原子切换并执行后端直连、Nginx、更新 path unit 和静态首页健康检查;成功后页面倒计时 10 秒自动刷新,安装中刷新或短暂断线会恢复 3 秒轮询;失败自动恢复并复验上一版本 | 10 秒是页面刷新等待,不延迟服务端安装;真实 Linux systemd 主机仍须执行发布后冒烟和备份恢复演练 |
| 凭据保护 | Token 只从权限 `0600` 的 root 配置/Token 文件读取,curl 通过临时 Header 文件使用;认证请求不跟随重定向,Token 不进入进程参数、页面、状态 JSON、审计参数或日志 | Token 轮换时必须同步更新 `/etc/kaidi/kaidi.env` 和 `/etc/kaidi/update.env` | | 凭据保护 | Token 只从权限 `0600` 的 root 配置/Token 文件读取,curl 通过临时 Header 文件使用;认证请求不跟随重定向,Token 不进入进程参数、页面、状态 JSON、审计参数或日志 | Token 轮换时必须同步更新 `/etc/kaidi/kaidi.env` 和 `/etc/kaidi/update.env` |
| 接口与自动化 | OpenAPI 为 `206 paths / 287 schemas`;后端全量 `211/211`,Vitest `53/53`、完整 Playwright `183/183`、更新专项 Playwright `15/15` 通过;ShellCheck、Actionlint、安装、更新和 Gitea draft/恰好 9 资产/发布 fixture 通过 | 更新专项覆盖下载确认、安装弹窗、10 秒刷新、安装中刷新恢复、禁用状态和失败可见性 | | 接口与自动化 | OpenAPI 为 `206 paths / 287 schemas`;后端全量 `211/211`,Vitest `53/53`、完整 Playwright `183/183`、更新专项 Playwright `15/15` 通过;ShellCheck、Actionlint、安装、更新和 Gitea draft/恰好 9 资产/发布 fixture 通过 | 更新专项覆盖下载确认、安装弹窗、10 秒刷新、安装中刷新恢复、禁用状态和失败可见性 |
+1 -1
View File
@@ -272,7 +272,7 @@
"pageType": "business", "pageType": "business",
"pageTemplate": "system-update", "pageTemplate": "system-update",
"requiresAuth": true, "requiresAuth": true,
"description": "查看当前版本、获取签名更新包、立即重启并查询历史更新记录。", "description": "查看当前版本、独立获取版本信息、显式下载签名更新包、下载完成后安装重启并查询历史更新记录。",
"breadcrumb": ["系统治理", "系统更新"], "breadcrumb": ["系统治理", "系统更新"],
"roles": ["SYSTEM_ADMIN"], "roles": ["SYSTEM_ADMIN"],
"permission": "admin:update:view" "permission": "admin:update:view"
+66
View File
@@ -137,3 +137,69 @@ test('confirms completion after the setup response is interrupted by a service r
await expect(page.getByText('网络请求失败')).toHaveCount(0); await expect(page.getByText('网络请求失败')).toHaveCount(0);
await expect(page).toHaveURL(/\/login$/, { timeout: 15_000 }); await expect(page).toHaveURL(/\/login$/, { timeout: 15_000 });
}); });
test('leaves the completed wizard when post-completion status polling is unavailable', async ({ page }) => {
let completionStarted = false;
await page.route('**/api/v1/setup/**', async (route) => {
const request = route.request();
const pathname = new URL(request.url()).pathname;
if (pathname === '/api/v1/setup/status') {
if (completionStarted) {
await route.abort('connectionreset');
return;
}
await route.fulfill({
json: {
data: {
required: true,
locked: false,
ready: false,
supportedDatabaseTypes: ['MYSQL'],
message: '请完成安装',
},
},
});
return;
}
const body = request.postDataJSON() as Record<string, unknown>;
if (pathname.endsWith('/test-connection')) {
await route.fulfill({
json: {
data: {
successful: true,
databaseType: 'MYSQL',
serverVersion: '8.4.6',
schemaReady: true,
message: 'MySQL 8.4 连接、排序规则和完整迁移权限验证通过',
},
},
});
return;
}
expect(body.adminUsername).toBe('admin');
completionStarted = true;
await route.fulfill({
json: {
data: {
completed: true,
username: 'admin',
message: '安装完成,系统正在切换到正式模式',
restartAfterSeconds: 1,
},
},
});
});
await page.goto('/setup');
await page.getByLabel('数据库密码').fill('fixture-db-password');
await page.getByLabel('安装码').fill('fixture-setup-code');
await page.getByRole('button', { name: '测试连接' }).click();
await page.getByRole('button', { name: '下一步' }).click();
await page.getByLabel('管理员密码').fill('SetupAdmin@2026Strong');
await page.getByLabel('确认密码').fill('SetupAdmin@2026Strong');
await page.getByRole('button', { name: '完成安装' }).click();
await page.getByRole('button', { name: '确定', exact: true }).click();
await expect(page.getByText('安装完成', { exact: true })).toBeVisible();
await expect(page).toHaveURL(/\/login$/, { timeout: 5_000 });
});
+203 -23
View File
@@ -7,7 +7,7 @@ function envelope(data: unknown) {
return { data, requestId: '01M00000000000000000000090' }; return { data, requestId: '01M00000000000000000000090' };
} }
function session() { function session(canExecute = true) {
return { return {
authenticated: true, authenticated: true,
user: { user: {
@@ -19,14 +19,16 @@ function session() {
}, },
roles: [{ code: 'SYSTEM_ADMIN', name: '系统管理员', workbenchRoute: '/governance/settings' }], roles: [{ code: 'SYSTEM_ADMIN', name: '系统管理员', workbenchRoute: '/governance/settings' }],
activeRole: 'SYSTEM_ADMIN', activeRole: 'SYSTEM_ADMIN',
permissions, permissions: canExecute ? permissions : permissions.filter((permission) => permission !== 'admin:update:execute'),
}; };
} }
function updateView(state: string, checked: boolean, enabled = true, recoveryPending = false) { function updateView(state: string, checked: boolean, enabled = true, recoveryPending = false) {
const busy = [ const busy = [
'QUEUED',
'DOWNLOAD_QUEUED', 'DOWNLOAD_QUEUED',
'INSTALL_QUEUED', 'INSTALL_QUEUED',
'PRECHECKING',
'VERIFYING', 'VERIFYING',
'DOWNLOADING', 'DOWNLOADING',
'BACKING_UP', 'BACKING_UP',
@@ -58,6 +60,14 @@ function updateView(state: string, checked: boolean, enabled = true, recoveryPen
publishedAt: checked ? '2026-08-16T00:00:00Z' : null, publishedAt: checked ? '2026-08-16T00:00:00Z' : null,
checkedAt: checked ? '2026-08-16T00:01:00Z' : null, checkedAt: checked ? '2026-08-16T00:01:00Z' : null,
statusUpdatedAt: null, statusUpdatedAt: null,
downloadedBytes: state === 'READY' ? 10_485_760 : state === 'DOWNLOADING' ? 5_242_880 : 0,
totalBytes: ['DOWNLOAD_QUEUED', 'DOWNLOADING', 'VERIFYING', 'READY'].includes(state) ? 10_485_760 : null,
bytesPerSecond: state === 'DOWNLOADING' ? 1_048_576 : 0,
downloadPercent: state === 'READY' ? 100 : state === 'DOWNLOADING' ? 50 : 0,
restartExpectedSeconds: state === 'RUNNING' ? 10 : null,
events: checked
? [{ occurredAt: '2026-08-16T00:01:00Z', level: 'INFO', stage: state, message: `状态进入 ${state}` }]
: [],
allowedActions: allowedActions:
!enabled || recoveryPending || busy !enabled || recoveryPending || busy
? [] ? []
@@ -69,6 +79,15 @@ function updateView(state: string, checked: boolean, enabled = true, recoveryPen
}; };
} }
interface FixtureOptions {
canExecute?: boolean;
checkResponseState?: string;
downloadProgressReads?: number;
failDownloadResponse?: boolean;
failInstallResponse?: boolean;
restartOfflineReads?: number;
}
async function installFixture( async function installFixture(
page: Page, page: Page,
downloadBodies: unknown[], downloadBodies: unknown[],
@@ -78,9 +97,20 @@ async function installFixture(
completeAfterInstall = false, completeAfterInstall = false,
initialState?: string, initialState?: string,
completeBusyAfterFirstRead = false, completeBusyAfterFirstRead = false,
options: FixtureOptions = {},
) { ) {
const {
canExecute = true,
checkResponseState,
downloadProgressReads = 0,
failDownloadResponse = false,
failInstallResponse = false,
restartOfflineReads = 0,
} = options;
let checked = recoveryPending || Boolean(initialState); let checked = recoveryPending || Boolean(initialState);
let state = recoveryPending ? 'FAILED' : initialState || 'IDLE'; let state = recoveryPending ? 'RECOVERY_REQUIRED' : initialState || 'IDLE';
let progressDeadline = 0;
let restartDeadline = 0;
const history: Array<Record<string, unknown>> = []; const history: Array<Record<string, unknown>> = [];
const recordHistory = (actionCode: string, targetVersion = '1.0.0-preview.2') => { const recordHistory = (actionCode: string, targetVersion = '1.0.0-preview.2') => {
history.unshift({ history.unshift({
@@ -93,7 +123,7 @@ async function installFixture(
objectType: 'SYSTEM_UPDATE', objectType: 'SYSTEM_UPDATE',
objectPublicId: 'SYSTEM_UPDATE', objectPublicId: 'SYSTEM_UPDATE',
resultCode: 'SUCCESS', resultCode: 'SUCCESS',
reason: actionCode === 'SYSTEM_UPDATE_REQUEST' ? '管理员确认立即重启' : null, reason: actionCode === 'SYSTEM_UPDATE_REQUEST' ? '管理员确认立即更新并重启' : null,
beforeJson: null, beforeJson: null,
afterJson: JSON.stringify({ targetVersion }), afterJson: JSON.stringify({ targetVersion }),
occurredAt: '2026-08-16T00:02:00Z', occurredAt: '2026-08-16T00:02:00Z',
@@ -103,9 +133,9 @@ async function installFixture(
await page.route('**/api/v1/**', async (route: Route) => { await page.route('**/api/v1/**', async (route: Route) => {
const request = route.request(); const request = route.request();
const pathname = new URL(request.url()).pathname; const pathname = new URL(request.url()).pathname;
if (pathname === '/api/v1/auth/session') return route.fulfill({ json: envelope(session()) }); if (pathname === '/api/v1/auth/session') return route.fulfill({ json: envelope(session(canExecute)) });
if (pathname === '/api/v1/auth/profile') return route.fulfill({ json: envelope(session().user) }); if (pathname === '/api/v1/auth/profile') return route.fulfill({ json: envelope(session(canExecute).user) });
if (pathname === '/api/v1/auth/roles') return route.fulfill({ json: envelope(session().roles) }); if (pathname === '/api/v1/auth/roles') return route.fulfill({ json: envelope(session(canExecute).roles) });
if (pathname === '/api/v1/auth/csrf') { if (pathname === '/api/v1/auth/csrf') {
return route.fulfill({ return route.fulfill({
headers: { 'set-cookie': 'XSRF-TOKEN=update-csrf; Path=/; SameSite=Lax' }, headers: { 'set-cookie': 'XSRF-TOKEN=update-csrf; Path=/; SameSite=Lax' },
@@ -122,26 +152,43 @@ async function installFixture(
}); });
} }
if (pathname === '/api/v1/admin/system-update' && request.method() === 'GET') { if (pathname === '/api/v1/admin/system-update' && request.method() === 'GET') {
if (state === 'RUNNING' && Date.now() < restartDeadline) {
return route.abort('connectionrefused');
}
if (state === 'RUNNING' && restartDeadline > 0) state = 'SUCCEEDED';
const response = updateView(state, checked, enabled, recoveryPending); const response = updateView(state, checked, enabled, recoveryPending);
if (state === 'DOWNLOADING' && Date.now() >= progressDeadline) state = 'READY';
if (completeBusyAfterFirstRead && state === 'INSTALLING') state = 'SUCCEEDED'; if (completeBusyAfterFirstRead && state === 'INSTALLING') state = 'SUCCEEDED';
return route.fulfill({ json: envelope(response) }); return route.fulfill({ json: envelope(response) });
} }
if (pathname === '/api/v1/admin/system-update/check' && request.method() === 'POST') { if (pathname === '/api/v1/admin/system-update/check' && request.method() === 'POST') {
checked = true; checked = true;
recordHistory('SYSTEM_UPDATE_CHECK'); recordHistory('SYSTEM_UPDATE_CHECK');
return route.fulfill({ json: envelope(updateView(state, checked, enabled, recoveryPending)) }); if (checkResponseState) state = checkResponseState;
const response = updateView(state, checked, enabled, recoveryPending);
if (!canExecute) response.allowedActions = ['CHECK'];
return route.fulfill({ json: envelope(response) });
} }
if (pathname === '/api/v1/admin/system-update/download' && request.method() === 'POST') { if (pathname === '/api/v1/admin/system-update/download' && request.method() === 'POST') {
downloadBodies.push(request.postDataJSON()); downloadBodies.push(request.postDataJSON());
recordHistory('SYSTEM_UPDATE_DOWNLOAD_REQUEST'); recordHistory('SYSTEM_UPDATE_DOWNLOAD_REQUEST');
state = 'READY'; state = downloadProgressReads > 0 ? 'DOWNLOADING' : 'READY';
progressDeadline = Date.now() + downloadProgressReads * 1000;
if (failDownloadResponse) return route.abort('connectionreset');
return route.fulfill({ json: envelope(updateView('DOWNLOAD_QUEUED', true, enabled)) }); return route.fulfill({ json: envelope(updateView('DOWNLOAD_QUEUED', true, enabled)) });
} }
if (pathname === '/api/v1/admin/system-update/install' && request.method() === 'POST') { if (pathname === '/api/v1/admin/system-update/install' && request.method() === 'POST') {
installBodies.push(request.postDataJSON()); installBodies.push(request.postDataJSON());
recordHistory('SYSTEM_UPDATE_REQUEST'); recordHistory('SYSTEM_UPDATE_REQUEST');
const queued = updateView('INSTALL_QUEUED', true, enabled); const queued = updateView('INSTALL_QUEUED', true, enabled);
state = completeAfterInstall ? 'SUCCEEDED' : 'INSTALL_QUEUED'; restartDeadline = Date.now() + restartOfflineReads * 1000;
state =
restartOfflineReads > 0
? 'RUNNING'
: failInstallResponse || completeAfterInstall
? 'SUCCEEDED'
: 'INSTALL_QUEUED';
if (failInstallResponse) return route.abort('connectionreset');
return route.fulfill({ json: envelope(queued) }); return route.fulfill({ json: envelope(queued) });
} }
if (pathname === '/api/v1/audit/logs' && request.method() === 'GET') { if (pathname === '/api/v1/audit/logs' && request.method() === 'GET') {
@@ -158,7 +205,7 @@ async function installFixture(
}); });
} }
test('system administrator checks and queues a signed online update', async ({ page }) => { test('system administrator checks, downloads, and explicitly installs a signed online update', async ({ page }) => {
const downloadBodies: unknown[] = []; const downloadBodies: unknown[] = [];
const installBodies: unknown[] = []; const installBodies: unknown[] = [];
await installFixture(page, downloadBodies, installBodies); await installFixture(page, downloadBodies, installBodies);
@@ -166,16 +213,142 @@ test('system administrator checks and queues a signed online update', async ({ p
await expect(page.locator('h1.page-title-sr-only')).toHaveText('系统更新'); await expect(page.locator('h1.page-title-sr-only')).toHaveText('系统更新');
await expect(page.locator('.version-item').filter({ hasText: '当前版本' })).toContainText('1.0.0-preview.1'); await expect(page.locator('.version-item').filter({ hasText: '当前版本' })).toContainText('1.0.0-preview.1');
await page.getByRole('button', { name: '获取更新', exact: true }).click(); await page.getByRole('button', { name: '获取版本', exact: true }).click();
await expect(page.locator('.version-item').filter({ hasText: '最新版本' })).toContainText('1.0.0-preview.2'); await expect(page.locator('.version-item').filter({ hasText: '最新版本' })).toContainText('1.0.0-preview.2');
await expect(page.getByRole('button', { name: '立即重启', exact: true })).toBeVisible({ timeout: 5_000 }); await expect(page.getByRole('button', { name: '立即更新', exact: true })).toBeVisible({ timeout: 5_000 });
expect(downloadBodies).toEqual([{ version: '1.0.0-preview.2' }]); await expect(page.getByRole('button', { name: '立即更新并重启', exact: true })).toHaveCount(0);
await expect(page.getByText('下载更新包', { exact: true })).toBeVisible(); expect(downloadBodies).toEqual([]);
await page.getByRole('button', { name: '立即重启', exact: true }).click(); await page.getByRole('button', { name: '立即更新', exact: true }).click();
expect(downloadBodies).toEqual([{ version: '1.0.0-preview.2' }]);
const updateState = page.locator('.version-item').filter({ hasText: '更新状态' });
await expect(updateState.getByText('下载已排队', { exact: true })).toBeVisible();
await expect(page.getByText('已发现新版本,但当前账号没有下载权限', { exact: true })).toHaveCount(0);
await expect(updateState.getByText('下载完成', { exact: true })).toBeVisible({ timeout: 8_000 });
await expect(page.getByRole('button', { name: '立即更新并重启', exact: true })).toBeVisible();
await page.getByRole('button', { name: '立即更新并重启', exact: true }).click();
await expect(page.getByText('安装请求已排队', { exact: true })).toBeVisible(); await expect(page.getByText('安装请求已排队', { exact: true })).toBeVisible();
expect(installBodies).toEqual([{ version: '1.0.0-preview.2', reason: '管理员确认立即重启' }]); expect(installBodies).toEqual([{ version: '1.0.0-preview.2', reason: '管理员确认立即更新并重启' }]);
});
test('download dialog shows real byte progress and transfer speed without a false permission warning', async ({
page,
}) => {
await installFixture(page, [], [], true, false, false, undefined, false, { downloadProgressReads: 8 });
await page.goto('/governance/update');
await page.getByRole('button', { name: '获取版本', exact: true }).click();
await page.getByRole('button', { name: '立即更新', exact: true }).click();
const dialog = page.getByRole('dialog', { name: '系统更新' });
await expect(dialog.getByText('50%', { exact: true })).toBeVisible({ timeout: 5_000 });
await expect(dialog.getByText('1.0 MB/s', { exact: true })).toBeVisible();
await expect(dialog.getByText('已发现新版本,但当前账号没有下载权限', { exact: true })).toHaveCount(0);
await expect(dialog.getByRole('button', { name: '立即更新并重启', exact: true })).toBeVisible({ timeout: 12_000 });
});
test('restart dialog keeps counting down and reconnects while the backend is temporarily offline', async ({ page }) => {
await installFixture(page, [], [], true, false, false, 'READY', false, { restartOfflineReads: 8 });
await page.goto('/governance/update');
await page.getByRole('button', { name: '立即更新并重启', exact: true }).click();
const dialog = page.getByRole('dialog', { name: '系统更新' });
await expect(dialog.getByText('服务正在重启,页面会持续重连,不需要手动刷新。', { exact: false })).toBeVisible({
timeout: 5_000,
});
await expect(dialog.getByText('应用服务连接中断,正在等待进程重启', { exact: true })).toBeVisible();
await expect(dialog.getByText(/新版本已通过健康检查,页面将在 \d+ 秒后自动刷新。/)).toBeVisible({
timeout: 15_000,
});
});
test('rechecking a downloaded package prompts installation instead of downloading again', async ({ page }) => {
await installFixture(page, [], [], true, false, false, 'READY');
await page.goto('/governance/update');
await page.getByRole('button', { name: '获取版本', exact: true }).click();
await expect(page.getByText('更新包已下载完成,请点击“立即更新并重启”安装新版本', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: '立即更新', exact: true })).toHaveCount(0);
await expect(page.getByRole('button', { name: '立即更新并重启', exact: true })).toBeVisible();
});
test('view-only administrators see a download permission message', async ({ page }) => {
await installFixture(page, [], [], true, false, false, undefined, false, { canExecute: false });
await page.goto('/governance/update');
await page.getByRole('button', { name: '获取版本', exact: true }).click();
await expect(page.getByText('发现新版本,但当前账号没有下载权限', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: '立即更新', exact: true })).toHaveCount(0);
await expect(page.getByRole('button', { name: '立即更新并重启', exact: true })).toHaveCount(0);
});
test('a check response that is already queued is treated as busy instead of missing permission', async ({ page }) => {
await installFixture(page, [], [], true, false, false, undefined, false, {
checkResponseState: 'DOWNLOAD_QUEUED',
});
await page.goto('/governance/update');
await page.getByRole('button', { name: '获取版本', exact: true }).click();
await expect(page.getByRole('dialog', { name: '系统更新' })).toBeVisible();
await expect(page.getByText('发现新版本,但当前账号没有下载权限', { exact: true })).toHaveCount(0);
await expect(page.getByText('下载请求已排队', { exact: true }).first()).toBeVisible();
});
test('download and install continue polling after an accepted command loses its response', async ({ page }) => {
await installFixture(page, [], [], true, false, false, undefined, false, {
failDownloadResponse: true,
});
await page.goto('/governance/update');
await page.getByRole('button', { name: '获取版本', exact: true }).click();
await page.getByRole('button', { name: '立即更新', exact: true }).click();
await expect(
page.locator('.version-item').filter({ hasText: '更新状态' }).getByText('下载完成', { exact: true }),
).toBeVisible({ timeout: 8_000 });
await expect(page.getByRole('button', { name: '立即更新并重启', exact: true })).toBeVisible();
});
test('accepted install continues to the refresh countdown after its response is lost', async ({ page }) => {
await installFixture(page, [], [], true, false, false, undefined, false, {
failInstallResponse: true,
});
await page.goto('/governance/update');
await page.getByRole('button', { name: '获取版本', exact: true }).click();
await page.getByRole('button', { name: '立即更新', exact: true }).click();
await expect(
page.locator('.version-item').filter({ hasText: '更新状态' }).getByText('下载完成', { exact: true }),
).toBeVisible({ timeout: 8_000 });
await page.getByRole('button', { name: '立即更新并重启', exact: true }).click();
await expect(page.getByText('新版本已通过健康检查,页面将在 10 秒后自动刷新。', { exact: true })).toBeVisible({
timeout: 8_000,
});
});
test('a lost install response stays pending while the application restarts', async ({ page }) => {
await installFixture(page, [], [], true, false, false, 'READY', false, {
failInstallResponse: true,
restartOfflineReads: 4,
});
await page.goto('/governance/update');
await page.getByRole('button', { name: '立即更新并重启', exact: true }).click();
const dialog = page.getByRole('dialog', { name: '系统更新' });
await expect(dialog.getByText('立即更新并重启失败', { exact: false })).toHaveCount(0);
await expect(dialog.getByText('服务正在重启,页面会持续重连,不需要手动刷新。', { exact: false })).toBeVisible({
timeout: 5_000,
});
await expect(dialog.getByText(/新版本已通过健康检查,页面将在 \d+ 秒后自动刷新。/)).toBeVisible({
timeout: 10_000,
});
}); });
test('brand logo returns the active identity to its workbench', async ({ page }) => { test('brand logo returns the active identity to its workbench', async ({ page }) => {
@@ -193,8 +366,9 @@ test('disabled online updates expose status without an executable check action',
await page.goto('/governance/update'); await page.goto('/governance/update');
await expect(page.getByText('在线更新未配置', { exact: true })).toBeVisible(); await expect(page.getByText('在线更新未配置', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: '获取更新', exact: true })).toBeDisabled(); await expect(page.getByRole('button', { name: '获取版本', exact: true })).toBeDisabled();
await expect(page.getByRole('button', { name: '立即重启', exact: true })).toHaveCount(0); await expect(page.getByRole('button', { name: '立即更新', exact: true })).toHaveCount(0);
await expect(page.getByRole('button', { name: '立即更新并重启', exact: true })).toHaveCount(0);
}); });
test('rollback recovery keeps the failure visible without an install action', async ({ page }) => { test('rollback recovery keeps the failure visible without an install action', async ({ page }) => {
@@ -202,15 +376,19 @@ test('rollback recovery keeps the failure visible without an install action', as
await page.goto('/governance/update'); await page.goto('/governance/update');
await expect(page.getByText('回滚未完成,更新服务将重试', { exact: true })).toBeVisible(); await expect(page.getByText('回滚未完成,更新服务将重试', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: '立即重启', exact: true })).toHaveCount(0); await expect(page.getByRole('button', { name: '立即更新并重启', exact: true })).toHaveCount(0);
}); });
test('successful installation starts the ten-second automatic refresh countdown', async ({ page }) => { test('successful installation starts the ten-second automatic refresh countdown', async ({ page }) => {
await installFixture(page, [], [], true, false, true); await installFixture(page, [], [], true, false, true);
await page.goto('/governance/update'); await page.goto('/governance/update');
await page.getByRole('button', { name: '获取更新', exact: true }).click(); await page.getByRole('button', { name: '获取版本', exact: true }).click();
await page.getByRole('button', { name: '立即重启', exact: true }).click({ timeout: 5_000 }); await page.getByRole('button', { name: '立即更新', exact: true }).click({ timeout: 5_000 });
await expect(
page.locator('.version-item').filter({ hasText: '更新状态' }).getByText('下载完成', { exact: true }),
).toBeVisible({ timeout: 8_000 });
await page.getByRole('button', { name: '立即更新并重启', exact: true }).click();
await expect(page.getByText('新版本已通过健康检查,页面将在 10 秒后自动刷新。', { exact: true })).toBeVisible({ await expect(page.getByText('新版本已通过健康检查,页面将在 10 秒后自动刷新。', { exact: true })).toBeVisible({
timeout: 5_000, timeout: 5_000,
@@ -221,7 +399,9 @@ test('reloading during installation resumes polling and starts the refresh count
await installFixture(page, [], [], true, false, false, 'INSTALLING', true); await installFixture(page, [], [], true, false, false, 'INSTALLING', true);
await page.goto('/governance/update'); await page.goto('/governance/update');
await expect(page.getByText('安装中', { exact: true })).toBeVisible(); await expect(
page.locator('.version-item').filter({ hasText: '更新状态' }).getByText('安装中', { exact: true }),
).toBeVisible();
await expect(page.getByText('新版本已通过健康检查,页面将在 10 秒后自动刷新。', { exact: true })).toBeVisible({ await expect(page.getByText('新版本已通过健康检查,页面将在 10 秒后自动刷新。', { exact: true })).toBeVisible({
timeout: 6_000, timeout: 6_000,
}); });
+14
View File
@@ -2,6 +2,13 @@ import { request } from '@/utils/request';
import { commandHeaders } from './command'; import { commandHeaders } from './command';
export interface SystemUpdateEvent {
occurredAt: string;
level: 'INFO' | 'WARN' | 'ERROR';
stage: string;
message: string;
}
export interface SystemUpdateView { export interface SystemUpdateView {
enabled: boolean; enabled: boolean;
currentVersion: string; currentVersion: string;
@@ -13,6 +20,12 @@ export interface SystemUpdateView {
publishedAt?: string | null; publishedAt?: string | null;
checkedAt?: string | null; checkedAt?: string | null;
statusUpdatedAt?: string | null; statusUpdatedAt?: string | null;
downloadedBytes?: number | null;
totalBytes?: number | null;
bytesPerSecond?: number | null;
downloadPercent?: number | null;
restartExpectedSeconds?: number | null;
events: SystemUpdateEvent[];
allowedActions: string[]; allowedActions: string[];
} }
@@ -21,6 +34,7 @@ function normalize(value: SystemUpdateView): SystemUpdateView {
...value, ...value,
enabled: Boolean(value?.enabled), enabled: Boolean(value?.enabled),
updateAvailable: Boolean(value?.updateAvailable), updateAvailable: Boolean(value?.updateAvailable),
events: Array.isArray(value?.events) ? value.events : [],
allowedActions: Array.isArray(value?.allowedActions) ? value.allowedActions : [], allowedActions: Array.isArray(value?.allowedActions) ? value.allowedActions : [],
}; };
} }
@@ -29,45 +29,73 @@
<div class="update-actions"> <div class="update-actions">
<t-button <t-button
variant="outline" variant="outline"
:loading="fetchingUpdate" :loading="checkingUpdate"
:disabled="!canFetchUpdate || updateBusy || restarting" :disabled="!canCheckUpdate || checkingUpdate || downloadingUpdate || installingUpdate"
@click="fetchUpdate" @click="checkLatest"
> >
<template #icon><t-icon name="cloud-download" /></template> <template #icon><t-icon name="refresh" /></template>
获取更新 获取版本
</t-button> </t-button>
<t-button <t-button
v-if="canRestart" v-if="canDownloadUpdate"
theme="primary" theme="primary"
:loading="restarting" :loading="downloadingUpdate"
:disabled="updateBusy || fetchingUpdate" :disabled="checkingUpdate || downloadingUpdate || installingUpdate"
@click="restartNow" @click="downloadNow"
>
<template #icon><t-icon name="cloud-download" /></template>
立即更新
</t-button>
<t-button
v-if="canInstall && !updateDialogVisible"
theme="primary"
:loading="installingUpdate"
:disabled="checkingUpdate || downloadingUpdate || installingUpdate"
@click="installNow"
> >
<template #icon><t-icon name="poweroff" /></template> <template #icon><t-icon name="poweroff" /></template>
立即重启 立即更新并重启
</t-button> </t-button>
</div> </div>
</div> </div>
<t-steps :current="updateStep" :layout="stepLayout" status="process" class="update-steps"> <t-steps :current="updateStep" :layout="stepLayout" status="process" class="update-steps">
<t-step-item title="获取版本" content="检查最新发布" /> <t-step-item title="获取版本" content="检查最新发布" />
<t-step-item title="下载校验" content="下载并验证签名" /> <t-step-item title="下载更新" content="下载并验证签名" />
<t-step-item title="立即重启" content="备份并切换版本" /> <t-step-item title="安装重启" content="备份并切换版本" />
<t-step-item title="完成更新" content="健康检查后刷新" /> <t-step-item title="完成更新" content="健康检查后刷新" />
</t-steps> </t-steps>
<t-alert v-if="statusError" theme="error" :close-btn="false"> <div v-if="showDownloadProgress && !updateDialogVisible" class="download-progress" aria-live="polite">
<div class="alert-content"> <div class="download-progress__heading">
<span>{{ statusError }}</span> <span>更新包下载进度</span>
<t-link theme="primary" @click="refreshPage">重新加载</t-link> <strong>{{ updateProgress }}%</strong>
</div> </div>
</t-alert> <t-progress :percentage="updateProgress" :label="false" />
<t-alert v-else-if="updateRefreshSeconds !== null" theme="success" :close-btn="false" aria-live="polite"> <div class="download-progress__meta">
新版本已通过健康检查,页面将在 {{ updateRefreshSeconds }} 秒后自动刷新。 <span>{{ formatBytes(updateStatus?.downloadedBytes) }} / {{ formatBytes(updateStatus?.totalBytes) }}</span>
</t-alert> <span>{{ downloadSpeedLabel }}</span>
<t-alert v-else :theme="updateStatus?.enabled === false ? 'warning' : 'info'" :close-btn="false"> </div>
{{ updateStatus?.message || '正在读取系统版本状态' }} </div>
</t-alert>
<template v-if="!updateDialogVisible">
<t-alert v-if="statusError" theme="error" :close-btn="false">
<div class="alert-content">
<span>{{ statusError }}</span>
<t-link theme="primary" @click="refreshPage">重新加载</t-link>
</div>
</t-alert>
<t-alert v-else-if="updateRefreshSeconds !== null" theme="success" :close-btn="false" aria-live="polite">
新版本已通过健康检查,页面将在 {{ updateRefreshSeconds }} 秒后自动刷新。
</t-alert>
<t-alert v-else :theme="updateStatus?.enabled === false ? 'warning' : 'info'" :close-btn="false">
<div class="update-status-message">
<strong>{{ updateStateLabel }}</strong>
<span>{{ updateStatus?.message || '正在读取系统版本状态' }}</span>
<small v-if="updateActionHint">{{ updateActionHint }}</small>
</div>
</t-alert>
</template>
<div v-if="updateStatus?.releaseNotes" class="release-notes"> <div v-if="updateStatus?.releaseNotes" class="release-notes">
<span>版本说明</span> <span>版本说明</span>
@@ -109,16 +137,99 @@
</t-table> </t-table>
<t-empty v-else description="暂无系统更新记录" /> <t-empty v-else description="暂无系统更新记录" />
</section> </section>
<t-dialog
v-model:visible="updateDialogVisible"
aria-label="系统更新"
header="系统更新"
width="min(720px, calc(100vw - 32px))"
:footer="false"
:close-btn="dialogClosable"
:close-on-overlay-click="false"
:close-on-esc-keydown="dialogClosable"
>
<div class="update-dialog" role="dialog" aria-label="系统更新" aria-live="polite" aria-modal="true">
<t-steps :current="updateStep" :layout="stepLayout" status="process">
<t-step-item title="获取版本" content="确认目标版本" />
<t-step-item title="下载校验" content="下载并验证签名" />
<t-step-item title="安装重启" content="备份、切换、重启" />
<t-step-item title="完成" content="健康检查与刷新" />
</t-steps>
<div class="dialog-status-line">
<t-tag :theme="updateStateTheme" variant="light">{{ updateStateLabel }}</t-tag>
<span>{{ updateStatus?.message || '等待更新服务返回状态' }}</span>
</div>
<t-alert v-if="statusError" theme="error" :close-btn="false">{{ statusError }}</t-alert>
<t-alert v-else-if="installRequestUncertain" theme="warning" :close-btn="false">
安装请求连接中断,正在查询服务器确认是否已受理,请勿重复提交。
</t-alert>
<div v-if="showDownloadProgress" class="download-progress download-progress--dialog">
<div class="download-progress__heading">
<span>正在下载 {{ updateStatus?.latestVersion || updateStatus?.currentVersion }}</span>
<strong>{{ updateProgress }}%</strong>
</div>
<t-progress :percentage="updateProgress" :label="false" />
<div class="download-progress__meta">
<span>{{ formatBytes(updateStatus?.downloadedBytes) }} / {{ formatBytes(updateStatus?.totalBytes) }}</span>
<span>{{ downloadSpeedLabel }}</span>
</div>
</div>
<t-alert v-if="connectionInterrupted" theme="warning" :close-btn="false">
服务正在重启,页面会持续重连,不需要手动刷新。
<span v-if="restartCountdown !== null && restartCountdown > 0">预计 {{ restartCountdown }} 秒后恢复。</span>
<span v-else>预计时间已到,仍在等待服务恢复。</span>
</t-alert>
<t-alert v-else-if="restartCountdown !== null && installInProgress" theme="info" :close-btn="false">
应用进程正在切换,预计 {{ restartCountdown }} 秒后恢复访问。
</t-alert>
<t-alert v-else-if="updateRefreshSeconds !== null" theme="success" :close-btn="false">
新版本已通过健康检查,页面将在 {{ updateRefreshSeconds }} 秒后自动刷新。
</t-alert>
<t-alert v-else-if="updateStatus?.state === 'RECOVERY_REQUIRED'" theme="error" :close-btn="false">
自动回滚未恢复应用,已停止接受新的更新任务,请先完成服务器恢复。
</t-alert>
<section class="runtime-log" aria-label="更新运行日志">
<div class="runtime-log__heading">
<span>运行日志</span>
<small>{{ updateEvents.length }} 条</small>
</div>
<div class="runtime-log__body" role="log">
<div v-for="(event, index) in updateEvents" :key="`${event.occurredAt}-${index}`" class="runtime-log__row">
<time>{{ formatLogTime(event.occurredAt) }}</time>
<t-tag size="small" :theme="eventTheme(event.level)" variant="light">{{
eventStageLabel(event.stage)
}}</t-tag>
<span>{{ event.message }}</span>
</div>
<t-empty v-if="!updateEvents.length" description="等待更新服务输出日志" />
</div>
</section>
<div class="dialog-actions">
<t-button v-if="canInstall" theme="primary" :loading="installingUpdate" @click="installNow">
<template #icon><t-icon name="poweroff" /></template>
立即更新并重启
</t-button>
<t-button v-if="dialogClosable" variant="outline" @click="updateDialogVisible = false">关闭</t-button>
</div>
</div>
</t-dialog>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { isAxiosError } from 'axios';
import type { PrimaryTableCol } from 'tdesign-vue-next'; import type { PrimaryTableCol } from 'tdesign-vue-next';
import { MessagePlugin } from 'tdesign-vue-next'; import { MessagePlugin } from 'tdesign-vue-next';
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'; import { computed, onBeforeUnmount, onMounted, ref } from 'vue';
import type { AuditLog } from '@/api/audit'; import type { AuditLog } from '@/api/audit';
import { getAuditLogs } from '@/api/audit'; import { getAuditLogs } from '@/api/audit';
import type { SystemUpdateView } from '@/api/system-update'; import type { SystemUpdateEvent, SystemUpdateView } from '@/api/system-update';
import { import {
checkSystemUpdate, checkSystemUpdate,
downloadSystemUpdate, downloadSystemUpdate,
@@ -129,35 +240,63 @@ import {
defineOptions({ name: 'SystemUpdatePage' }); defineOptions({ name: 'SystemUpdatePage' });
type TagTheme = 'default' | 'primary' | 'success' | 'warning' | 'danger'; type TagTheme = 'default' | 'primary' | 'success' | 'warning' | 'danger';
const UPDATE_PENDING_KEY = 'kaidi-system-update-pending';
const updateStatus = ref<SystemUpdateView | null>(null); const updateStatus = ref<SystemUpdateView | null>(null);
const isNarrow = ref(false); const isNarrow = ref(false);
const statusLoading = ref(false); const statusLoading = ref(false);
const fetchingUpdate = ref(false); const checkingUpdate = ref(false);
const restarting = ref(false); const downloadingUpdate = ref(false);
const installingUpdate = ref(false);
const statusError = ref(''); const statusError = ref('');
const historyRows = ref<AuditLog[]>([]); const historyRows = ref<AuditLog[]>([]);
const historyLoading = ref(false); const historyLoading = ref(false);
const historyError = ref(''); const historyError = ref('');
const updateRefreshSeconds = ref<number | null>(null); const updateRefreshSeconds = ref<number | null>(null);
const restartCountdown = ref<number | null>(null);
const updateDialogVisible = ref(false);
const connectionInterrupted = ref(false);
const localEvents = ref<SystemUpdateEvent[]>([]);
const awaitingRefresh = ref(false); const awaitingRefresh = ref(false);
const installRequestUncertain = ref(false);
let pollTimer: ReturnType<typeof setInterval> | undefined; let pollTimer: ReturnType<typeof setInterval> | undefined;
let refreshTimer: ReturnType<typeof setInterval> | undefined; let refreshTimer: ReturnType<typeof setInterval> | undefined;
let restartTimer: ReturnType<typeof setInterval> | undefined;
const busyStates = new Set([ const busyStates = new Set([
'QUEUED', 'QUEUED',
'DOWNLOAD_QUEUED', 'DOWNLOAD_QUEUED',
'INSTALL_QUEUED', 'INSTALL_QUEUED',
'PRECHECKING',
'VERIFYING', 'VERIFYING',
'DOWNLOADING', 'DOWNLOADING',
'BACKING_UP', 'BACKING_UP',
'INSTALLING', 'INSTALLING',
'RUNNING', 'RUNNING',
]); ]);
const installStates = new Set(['INSTALL_QUEUED', 'BACKING_UP', 'INSTALLING', 'RUNNING']); const installStates = new Set(['INSTALL_QUEUED', 'PRECHECKING', 'BACKING_UP', 'INSTALLING', 'RUNNING']);
const updateBusy = computed(() => busyStates.has(updateStatus.value?.state || '')); const updateBusy = computed(() => busyStates.has(updateStatus.value?.state || ''));
const installInProgress = computed(
() => installStates.has(updateStatus.value?.state || '') || connectionInterrupted.value,
);
const dialogClosable = computed(() => !updateBusy.value && !connectionInterrupted.value);
const showDownloadProgress = computed(() =>
['DOWNLOAD_QUEUED', 'DOWNLOADING', 'VERIFYING', 'READY'].includes(updateStatus.value?.state || ''),
);
const updateProgress = computed(() => {
const value = Number(updateStatus.value?.downloadPercent ?? 0);
return Math.min(100, Math.max(0, Number.isFinite(value) ? Math.round(value) : 0));
});
const downloadSpeedLabel = computed(() =>
updateStatus.value?.state === 'READY' ? '下载完成' : formatSpeed(updateStatus.value?.bytesPerSecond),
);
const updateEvents = computed(() =>
[...(updateStatus.value?.events || []), ...localEvents.value]
.sort((left, right) => left.occurredAt.localeCompare(right.occurredAt))
.slice(-120),
);
const stepLayout = computed(() => (isNarrow.value ? 'vertical' : 'horizontal')); const stepLayout = computed(() => (isNarrow.value ? 'vertical' : 'horizontal'));
const currentIsLatest = computed( const currentIsLatest = computed(
() => () =>
@@ -165,16 +304,29 @@ const currentIsLatest = computed(
Boolean(updateStatus.value.latestVersion) && Boolean(updateStatus.value.latestVersion) &&
!updateStatus.value.updateAvailable && !updateStatus.value.updateAvailable &&
!updateBusy.value && !updateBusy.value &&
!['FAILED', 'UNKNOWN'].includes(updateStatus.value.state), !['FAILED', 'RECOVERY_REQUIRED', 'UNKNOWN'].includes(updateStatus.value.state),
); );
const canFetchUpdate = computed( const canCheckUpdate = computed(
() => () =>
updateStatus.value?.enabled !== false && updateStatus.value?.enabled !== false &&
updateStatus.value?.state !== 'READY' && !updateBusy.value &&
(updateStatus.value?.allowedActions.includes('CHECK') === true || updateStatus.value?.allowedActions.includes('CHECK') === true,
updateStatus.value?.allowedActions.includes('DOWNLOAD') === true), );
const canDownloadUpdate = computed(
() =>
updateStatus.value?.enabled !== false &&
!updateBusy.value &&
Boolean(updateStatus.value?.latestVersion) &&
updateStatus.value?.updateAvailable === true &&
updateStatus.value?.allowedActions.includes('DOWNLOAD') === true,
);
const canInstall = computed(
() =>
updateStatus.value?.enabled !== false &&
!updateBusy.value &&
updateStatus.value?.state === 'READY' &&
updateStatus.value?.allowedActions.includes('INSTALL') === true,
); );
const canRestart = computed(() => updateStatus.value?.allowedActions.includes('INSTALL') === true);
const updateStep = computed(() => { const updateStep = computed(() => {
const state = updateStatus.value?.state || 'IDLE'; const state = updateStatus.value?.state || 'IDLE';
if (state === 'SUCCEEDED' || state === 'CURRENT' || currentIsLatest.value) return 3; if (state === 'SUCCEEDED' || state === 'CURRENT' || currentIsLatest.value) return 3;
@@ -190,26 +342,43 @@ const updateStateLabel = computed(() => {
DISABLED: '未启用', DISABLED: '未启用',
CURRENT: '已是最新', CURRENT: '已是最新',
QUEUED: '已排队', QUEUED: '已排队',
DOWNLOAD_QUEUED: '等待下载', DOWNLOAD_QUEUED: '下载已排队',
INSTALL_QUEUED: '等待重启', INSTALL_QUEUED: '等待重启',
PRECHECKING: '安装预检',
VERIFYING: '校验中', VERIFYING: '校验中',
DOWNLOADING: '下载中', DOWNLOADING: '下载中',
READY: '等待重启', READY: '下载完成',
BACKING_UP: '备份中', BACKING_UP: '备份中',
INSTALLING: '安装中', INSTALLING: '安装中',
RUNNING: '重启中', RUNNING: '重启中',
SUCCEEDED: '更新成功', SUCCEEDED: '更新成功',
FAILED: '更新失败', FAILED: '更新失败',
RECOVERY_REQUIRED: '需要人工恢复',
UNKNOWN: '状态未知', UNKNOWN: '状态未知',
}[updateStatus.value?.state || 'IDLE'] || }[updateStatus.value?.state || 'IDLE'] ||
updateStatus.value?.state || updateStatus.value?.state ||
'待获取' '待获取'
); );
}); });
const updateActionHint = computed(() => {
const state = updateStatus.value?.state || 'IDLE';
if (['DOWNLOAD_QUEUED', 'VERIFYING', 'DOWNLOADING'].includes(state)) return '更新包正在下载和校验,请稍候。';
if (['INSTALL_QUEUED', 'PRECHECKING', 'BACKING_UP', 'INSTALLING', 'RUNNING'].includes(state)) {
return '更新包已确认,系统正在预检、备份、切换并重启。';
}
if (state === 'RECOVERY_REQUIRED') return '自动回滚未完成,新的更新操作已锁定。';
if (state === 'READY') {
return canInstall.value ? '下载完成,请点击“立即更新并重启”安装新版本。' : '下载完成,但当前账号没有安装权限。';
}
if (canDownloadUpdate.value) return '已发现新版本,请点击“立即更新”开始下载。';
if (updateStatus.value?.updateAvailable) return '已发现新版本,但当前账号没有下载权限。';
if (state === 'IDLE' && !updateStatus.value?.latestVersion) return '点击“获取版本”检查最新发布。';
return '';
});
const updateStateTheme = computed<TagTheme>(() => { const updateStateTheme = computed<TagTheme>(() => {
const state = updateStatus.value?.state || 'IDLE'; const state = updateStatus.value?.state || 'IDLE';
if (['SUCCEEDED', 'CURRENT', 'READY'].includes(state) || currentIsLatest.value) return 'success'; if (['SUCCEEDED', 'CURRENT', 'READY'].includes(state) || currentIsLatest.value) return 'success';
if (['FAILED', 'UNKNOWN'].includes(state)) return 'danger'; if (['FAILED', 'RECOVERY_REQUIRED', 'UNKNOWN'].includes(state)) return 'danger';
if (updateBusy.value) return 'warning'; if (updateBusy.value) return 'warning';
return 'default'; return 'default';
}); });
@@ -230,13 +399,37 @@ async function loadStatus(silent = false) {
} }
try { try {
const status = await getSystemUpdateStatus(); const status = await getSystemUpdateStatus();
if (connectionInterrupted.value) {
appendLocalEvent('INFO', 'RUNNING', '应用服务连接已恢复,正在确认更新结果');
connectionInterrupted.value = false;
}
updateStatus.value = status; updateStatus.value = status;
if (installStates.has(status.state)) awaitingRefresh.value = true; if (installStates.has(status.state)) {
awaitingRefresh.value = true;
updateDialogVisible.value = true;
installRequestUncertain.value = false;
statusError.value = '';
}
if (status.state === 'RUNNING') {
startRestartCountdown(status.restartExpectedSeconds ?? 10);
} else if (!installStates.has(status.state)) {
stopRestartCountdown();
}
if (status.state === 'RECOVERY_REQUIRED') updateDialogVisible.value = true;
handleCompletion(status); handleCompletion(status);
if (busyStates.has(status.state)) startPolling(); if (busyStates.has(status.state) || downloadingUpdate.value || installingUpdate.value) startPolling();
else stopPolling(); else stopPolling();
} catch (error) { } catch (error) {
if (!silent) statusError.value = friendlyError(error, '系统版本状态读取失败'); const restartExpected = awaitingRefresh.value || installStates.has(updateStatus.value?.state || '');
if (restartExpected) {
if (!connectionInterrupted.value) appendLocalEvent('WARN', 'RUNNING', '应用服务连接中断,正在等待进程重启');
connectionInterrupted.value = true;
updateDialogVisible.value = true;
startRestartCountdown(updateStatus.value?.restartExpectedSeconds ?? 10);
startPolling();
} else if (!silent) {
statusError.value = friendlyError(error, '系统版本状态读取失败');
}
} finally { } finally {
if (!silent) statusLoading.value = false; if (!silent) statusLoading.value = false;
} }
@@ -266,9 +459,9 @@ async function refreshPage() {
await Promise.all([loadStatus(), loadHistory()]); await Promise.all([loadStatus(), loadHistory()]);
} }
async function fetchUpdate() { async function checkLatest() {
if (fetchingUpdate.value || updateBusy.value || !canFetchUpdate.value) return; if (checkingUpdate.value || updateBusy.value || !canCheckUpdate.value) return;
fetchingUpdate.value = true; checkingUpdate.value = true;
statusError.value = ''; statusError.value = '';
try { try {
const checked = await checkSystemUpdate(); const checked = await checkSystemUpdate();
@@ -278,42 +471,88 @@ async function fetchUpdate() {
MessagePlugin.info('当前已是最新版本'); MessagePlugin.info('当前已是最新版本');
return; return;
} }
if (!checked.latestVersion || !checked.allowedActions.includes('DOWNLOAD')) { if (checked.state === 'READY') {
throw new Error('发现新版本,但当前账号没有下载更新包的权限'); MessagePlugin.success(
checked.allowedActions.includes('INSTALL')
? '更新包已下载完成,请点击“立即更新并重启”安装新版本'
: '更新包已下载完成,但当前账号没有安装权限',
);
} else if (busyStates.has(checked.state)) {
updateDialogVisible.value = true;
startPolling();
MessagePlugin.info(checked.message || '更新任务正在处理中,请查看当前进度');
} else if (!checked.allowedActions.includes('DOWNLOAD')) {
MessagePlugin.info('发现新版本,但当前账号没有下载权限');
} else {
MessagePlugin.success(`发现新版本 ${checked.latestVersion},请点击“立即更新”开始下载`);
} }
updateStatus.value = await downloadSystemUpdate(checked.latestVersion);
await loadHistory(true);
MessagePlugin.success('更新包已开始下载,下载和签名校验完成后可立即重启');
startPolling();
} catch (error) { } catch (error) {
statusError.value = friendlyError(error, '获取更新失败'); statusError.value = friendlyError(error, '获取版本失败');
} finally { } finally {
fetchingUpdate.value = false; checkingUpdate.value = false;
} }
} }
async function restartNow() { async function downloadNow() {
const version = updateStatus.value?.latestVersion; const version = updateStatus.value?.latestVersion;
if (!version || restarting.value || !canRestart.value) return; if (!version || downloadingUpdate.value || !canDownloadUpdate.value) return;
restarting.value = true; downloadingUpdate.value = true;
updateDialogVisible.value = true;
localEvents.value = [];
statusError.value = '';
startPolling();
try {
updateStatus.value = await downloadSystemUpdate(version);
appendLocalEvent('INFO', 'DOWNLOAD_QUEUED', `版本 ${version} 的下载请求已提交`);
MessagePlugin.success('更新包已开始下载,完成后可点击“立即更新并重启”');
void loadHistory(true);
} catch (error) {
statusError.value = friendlyError(error, '下载更新包失败');
void loadStatus(true);
} finally {
downloadingUpdate.value = false;
startPolling();
}
}
async function installNow() {
const version = updateStatus.value?.latestVersion;
if (!version || installingUpdate.value || !canInstall.value) return;
installingUpdate.value = true;
updateDialogVisible.value = true;
statusError.value = ''; statusError.value = '';
stopRefreshCountdown(); stopRefreshCountdown();
stopRestartCountdown();
awaitingRefresh.value = true;
installRequestUncertain.value = false;
setPendingUpdate(true);
startPolling();
try { try {
updateStatus.value = await installSystemUpdate(version, '管理员确认立即重启'); updateStatus.value = await installSystemUpdate(version, '管理员确认立即更新并重启');
awaitingRefresh.value = true; appendLocalEvent('INFO', 'INSTALL_QUEUED', `已确认安装 ${version},等待更新服务执行`);
MessagePlugin.success('重启任务已提交,系统恢复后页面将自动刷新'); MessagePlugin.success('更新任务已提交,系统完成切换并重启后页面将自动刷新');
await loadHistory(true); void loadHistory(true);
startPolling();
} catch (error) { } catch (error) {
statusError.value = friendlyError(error, '立即重启失败'); if (responseMayHaveBeenLost(error)) {
statusError.value = '';
installRequestUncertain.value = true;
appendLocalEvent('WARN', 'INSTALL_QUEUED', '安装请求连接中断,正在确认服务器是否已受理');
} else {
awaitingRefresh.value = false;
installRequestUncertain.value = false;
setPendingUpdate(false);
statusError.value = friendlyError(error, '立即更新并重启失败');
}
void loadStatus(true);
} finally { } finally {
restarting.value = false; installingUpdate.value = false;
startPolling();
} }
} }
function startPolling() { function startPolling() {
if (pollTimer) return; if (pollTimer) return;
pollTimer = setInterval(() => void loadStatus(true), 3000); pollTimer = setInterval(() => void loadStatus(true), 1000);
} }
function stopPolling() { function stopPolling() {
@@ -323,18 +562,66 @@ function stopPolling() {
function handleCompletion(status: SystemUpdateView) { function handleCompletion(status: SystemUpdateView) {
if (!awaitingRefresh.value) return; if (!awaitingRefresh.value) return;
if (status.state === 'SUCCEEDED') { if (status.state === 'READY') {
awaitingRefresh.value = false; awaitingRefresh.value = false;
installRequestUncertain.value = false;
setPendingUpdate(false);
stopRestartCountdown();
return;
}
if (status.state === 'SUCCEEDED') {
statusError.value = '';
awaitingRefresh.value = false;
connectionInterrupted.value = false;
installRequestUncertain.value = false;
setPendingUpdate(false);
stopRestartCountdown();
startRefreshCountdown(); startRefreshCountdown();
void loadHistory(true); void loadHistory(true);
return; return;
} }
if (['FAILED', 'CURRENT', 'DISABLED', 'UNKNOWN'].includes(status.state)) { if (['FAILED', 'RECOVERY_REQUIRED', 'CURRENT', 'DISABLED', 'UNKNOWN'].includes(status.state)) {
awaitingRefresh.value = false; awaitingRefresh.value = false;
connectionInterrupted.value = false;
installRequestUncertain.value = false;
setPendingUpdate(false);
stopRestartCountdown();
stopRefreshCountdown(); stopRefreshCountdown();
} }
} }
function startRestartCountdown(seconds: number) {
if (restartTimer) return;
restartCountdown.value = Math.max(0, Math.min(300, Math.round(seconds)));
restartTimer = setInterval(() => {
if (restartCountdown.value === null || restartCountdown.value <= 0) return;
restartCountdown.value -= 1;
}, 1000);
}
function stopRestartCountdown() {
if (restartTimer) clearInterval(restartTimer);
restartTimer = undefined;
restartCountdown.value = null;
}
function setPendingUpdate(pending: boolean) {
try {
if (pending) sessionStorage.setItem(UPDATE_PENDING_KEY, 'true');
else sessionStorage.removeItem(UPDATE_PENDING_KEY);
} catch {
// The in-memory state still keeps the current page resilient when storage is unavailable.
}
}
function hasPendingUpdate() {
try {
return sessionStorage.getItem(UPDATE_PENDING_KEY) === 'true';
} catch {
return false;
}
}
function startRefreshCountdown() { function startRefreshCountdown() {
if (refreshTimer) return; if (refreshTimer) return;
updateRefreshSeconds.value = 10; updateRefreshSeconds.value = 10;
@@ -355,6 +642,64 @@ function stopRefreshCountdown() {
updateRefreshSeconds.value = null; updateRefreshSeconds.value = null;
} }
function appendLocalEvent(level: SystemUpdateEvent['level'], stage: string, message: string) {
const latest = localEvents.value.at(-1);
if (latest?.stage === stage && latest.message === message) return;
localEvents.value = [...localEvents.value, { occurredAt: new Date().toISOString(), level, stage, message }].slice(
-30,
);
}
function formatBytes(value?: number | null) {
if (value === null || value === undefined || !Number.isFinite(value) || value < 0) return '待获取';
if (value < 1024) return `${Math.round(value)} B`;
const units = ['KB', 'MB', 'GB', 'TB'];
let amount = value / 1024;
let unit = 0;
while (amount >= 1024 && unit < units.length - 1) {
amount /= 1024;
unit += 1;
}
return `${amount >= 100 ? amount.toFixed(0) : amount.toFixed(1)} ${units[unit]}`;
}
function formatSpeed(value?: number | null) {
if (value === null || value === undefined || value <= 0) return '正在计算网速';
return `${formatBytes(value)}/s`;
}
function formatLogTime(value: string) {
const date = new Date(value);
return Number.isNaN(date.getTime())
? value
: date.toLocaleTimeString('zh-CN', { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' });
}
function eventTheme(level: SystemUpdateEvent['level']): TagTheme {
if (level === 'ERROR') return 'danger';
if (level === 'WARN') return 'warning';
return 'primary';
}
function eventStageLabel(stage: string) {
return (
{
DOWNLOAD_QUEUED: '排队',
VERIFYING: '校验',
DOWNLOADING: '下载',
READY: '就绪',
INSTALL_QUEUED: '确认',
PRECHECKING: '预检',
BACKING_UP: '备份',
INSTALLING: '安装',
RUNNING: '重启',
SUCCEEDED: '完成',
FAILED: '失败',
RECOVERY_REQUIRED: '恢复',
}[stage] || stage
);
}
function historyVersion(row: AuditLog) { function historyVersion(row: AuditLog) {
for (const source of [row.afterJson, row.beforeJson]) { for (const source of [row.afterJson, row.beforeJson]) {
if (!source) continue; if (!source) continue;
@@ -374,7 +719,7 @@ function actionLabel(action: string) {
{ {
SYSTEM_UPDATE_CHECK: '获取版本', SYSTEM_UPDATE_CHECK: '获取版本',
SYSTEM_UPDATE_DOWNLOAD_REQUEST: '下载更新包', SYSTEM_UPDATE_DOWNLOAD_REQUEST: '下载更新包',
SYSTEM_UPDATE_REQUEST: '立即重启', SYSTEM_UPDATE_REQUEST: '立即更新并重启',
}[action] || action }[action] || action
); );
} }
@@ -400,6 +745,12 @@ function friendlyError(error: unknown, fallback: string) {
return (error as Error)?.message || fallback; return (error as Error)?.message || fallback;
} }
function responseMayHaveBeenLost(error: unknown) {
return (
(isAxiosError(error) && !error.response) || (error as { transportFailure?: boolean })?.transportFailure === true
);
}
function updateViewportMode() { function updateViewportMode() {
isNarrow.value = window.innerWidth <= 640; isNarrow.value = window.innerWidth <= 640;
} }
@@ -407,11 +758,18 @@ function updateViewportMode() {
onMounted(() => { onMounted(() => {
updateViewportMode(); updateViewportMode();
window.addEventListener('resize', updateViewportMode); window.addEventListener('resize', updateViewportMode);
if (hasPendingUpdate()) {
awaitingRefresh.value = true;
updateDialogVisible.value = true;
startRestartCountdown(10);
startPolling();
}
void refreshPage(); void refreshPage();
}); });
onBeforeUnmount(() => { onBeforeUnmount(() => {
stopPolling(); stopPolling();
stopRefreshCountdown(); stopRefreshCountdown();
stopRestartCountdown();
window.removeEventListener('resize', updateViewportMode); window.removeEventListener('resize', updateViewportMode);
}); });
</script> </script>
@@ -503,6 +861,17 @@ onBeforeUnmount(() => {
border-top: 1px solid var(--td-component-border); border-top: 1px solid var(--td-component-border);
} }
.update-status-message {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 4px 10px;
}
.update-status-message small {
color: var(--td-text-color-secondary);
}
.release-notes span, .release-notes span,
.section-heading p, .section-heading p,
.section-heading > span { .section-heading > span {
@@ -534,6 +903,103 @@ onBeforeUnmount(() => {
width: 100%; width: 100%;
} }
.download-progress {
display: flex;
flex-direction: column;
gap: 8px;
padding: 14px 16px;
background: var(--td-bg-color-secondarycontainer);
border: 1px solid var(--td-component-border);
border-radius: 6px;
}
.download-progress__heading,
.download-progress__meta,
.runtime-log__heading,
.dialog-status-line,
.dialog-actions {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.download-progress__heading strong {
font-variant-numeric: tabular-nums;
}
.download-progress__meta {
color: var(--td-text-color-secondary);
font-size: 13px;
}
.update-dialog {
display: flex;
flex-direction: column;
gap: 18px;
min-width: 0;
}
.dialog-status-line {
justify-content: flex-start;
min-width: 0;
}
.dialog-status-line > span:last-child {
min-width: 0;
overflow-wrap: anywhere;
}
.runtime-log {
min-width: 0;
}
.runtime-log__heading {
margin-bottom: 8px;
}
.runtime-log__heading small {
color: var(--td-text-color-secondary);
}
.runtime-log__body {
display: flex;
flex-direction: column;
gap: 8px;
min-height: 120px;
max-height: 240px;
padding: 12px;
overflow: auto;
background: var(--td-bg-color-secondarycontainer);
border: 1px solid var(--td-component-border);
border-radius: 6px;
}
.runtime-log__row {
display: grid;
grid-template-columns: 72px 58px minmax(0, 1fr);
align-items: start;
gap: 8px;
color: var(--td-text-color-primary);
font-size: 13px;
line-height: 22px;
}
.runtime-log__row time {
color: var(--td-text-color-secondary);
font-variant-numeric: tabular-nums;
}
.runtime-log__row > span:last-child {
min-width: 0;
overflow-wrap: anywhere;
}
.dialog-actions {
justify-content: flex-end;
padding-top: 4px;
}
@media (width <= 900px) { @media (width <= 900px) {
.update-heading { .update-heading {
align-items: stretch; align-items: stretch;
@@ -571,5 +1037,23 @@ onBeforeUnmount(() => {
flex-direction: column; flex-direction: column;
gap: 8px; gap: 8px;
} }
.download-progress__meta,
.dialog-status-line,
.dialog-actions {
align-items: flex-start;
flex-direction: column;
}
.dialog-actions,
.dialog-actions :deep(.t-button) {
width: 100%;
}
.runtime-log__row {
grid-template-columns: 64px 52px minmax(0, 1fr);
gap: 6px;
font-size: 12px;
}
} }
</style> </style>
+8 -9
View File
@@ -378,19 +378,18 @@ function confirmSetup() {
function startCountdown() { function startCountdown() {
window.clearInterval(countdownTimer); window.clearInterval(countdownTimer);
countdownTimer = window.setInterval(() => { countdownTimer = window.setInterval(() => {
countdown.value -= 1; countdown.value = Math.max(0, countdown.value - 1);
if (countdown.value <= 0) void openLogin(); if (countdown.value === 0) openLogin();
}, 1000); }, 1000);
} }
async function openLogin() { function openLogin() {
window.clearInterval(countdownTimer); window.clearInterval(countdownTimer);
completionMessage.value = '系统正在启动,请稍候。'; countdown.value = 0;
if (await waitForSetupCompletion()) { completionMessage.value = '正在进入登录页。';
await router.replace('/login'); // A full navigation clears the setup-mode SPA state retained across the
return; // service restart. The login route guard performs the final setup check.
} window.location.replace('/login');
completionMessage.value = '系统启动时间较长,请稍后刷新页面。';
} }
onMounted(async () => { onMounted(async () => {
+1
View File
@@ -325,6 +325,7 @@ export class VAxios {
status: e.response?.status, status: e.response?.status,
requestId, requestId,
fieldErrors: problem?.fieldErrors, fieldErrors: problem?.fieldErrors,
transportFailure: !e.response,
}); });
if (e.response?.status === 401 && window.location.pathname !== '/login') { if (e.response?.status === 401 && window.location.pathname !== '/login') {
window.dispatchEvent(new CustomEvent('kaidi:session-expired')); window.dispatchEvent(new CustomEvent('kaidi:session-expired'));
+31
View File
@@ -5967,6 +5967,18 @@ components:
format: int64 format: int64
type: integer type: integer
type: object type: object
SystemUpdateEventView:
properties:
level:
type: string
message:
type: string
occurredAt:
format: date-time
type: string
stage:
type: string
type: object
SystemUpdateView: SystemUpdateView:
properties: properties:
allowedActions: allowedActions:
@@ -5976,10 +5988,23 @@ components:
checkedAt: checkedAt:
format: date-time format: date-time
type: string type: string
bytesPerSecond:
format: int64
type: integer
currentVersion: currentVersion:
type: string type: string
enabled: enabled:
type: boolean type: boolean
downloadPercent:
format: int32
type: integer
downloadedBytes:
format: int64
type: integer
events:
items:
"$ref": "#/components/schemas/SystemUpdateEventView"
type: array
latestVersion: latestVersion:
type: string type: string
message: message:
@@ -5989,11 +6014,17 @@ components:
type: string type: string
releaseNotes: releaseNotes:
type: string type: string
restartExpectedSeconds:
format: int32
type: integer
state: state:
type: string type: string
statusUpdatedAt: statusUpdatedAt:
format: date-time format: date-time
type: string type: string
totalBytes:
format: int64
type: integer
updateAvailable: updateAvailable:
type: boolean type: boolean
type: object type: object
+4 -1
View File
@@ -105,6 +105,7 @@ chmod 0755 "$STAGE/ops/update.sh" "$STAGE/ops/baota-start.sh" "$STAGE/ops/baota-
ARTIFACT="kaidi-finance-$VERSION.tar.gz" ARTIFACT="kaidi-finance-$VERSION.tar.gz"
COPYFILE_DISABLE=1 tar --format=ustar -czf "$OUTPUT_DIR/$ARTIFACT" -C "$STAGE" . COPYFILE_DISABLE=1 tar --format=ustar -czf "$OUTPUT_DIR/$ARTIFACT" -C "$STAGE" .
SHA256=$(sha256_file "$OUTPUT_DIR/$ARTIFACT") SHA256=$(sha256_file "$OUTPUT_DIR/$ARTIFACT")
ARTIFACT_SIZE_BYTES=$(wc -c < "$OUTPUT_DIR/$ARTIFACT" | tr -d '[:space:]')
cp "$ROOT/backend/target/backend-sbom.json" "$OUTPUT_DIR/backend-sbom.cdx.json" cp "$ROOT/backend/target/backend-sbom.json" "$OUTPUT_DIR/backend-sbom.cdx.json"
(cd "$ROOT/frontend" && npm sbom --omit=dev --package-lock-only \ (cd "$ROOT/frontend" && npm sbom --omit=dev --package-lock-only \
--sbom-format cyclonedx --sbom-type application) > "$OUTPUT_DIR/frontend-sbom.cdx.json" --sbom-format cyclonedx --sbom-type application) > "$OUTPUT_DIR/frontend-sbom.cdx.json"
@@ -167,7 +168,8 @@ EOF
BOOTSTRAP_SHA256=$(sha256_file "$OUTPUT_DIR/bootstrap-checksums.txt") BOOTSTRAP_SHA256=$(sha256_file "$OUTPUT_DIR/bootstrap-checksums.txt")
RELEASE_NOTES_VALUE=${KAIDI_RELEASE_NOTES:-"Kaidi Finance Preview $VERSION"} RELEASE_NOTES_VALUE=${KAIDI_RELEASE_NOTES:-"Kaidi Finance Preview $VERSION"}
VERSION="$VERSION" ARTIFACT="$ARTIFACT" SHA256="$SHA256" RELEASE_NOTES="$RELEASE_NOTES_VALUE" \ VERSION="$VERSION" ARTIFACT="$ARTIFACT" SHA256="$SHA256" ARTIFACT_SIZE_BYTES="$ARTIFACT_SIZE_BYTES" \
RELEASE_NOTES="$RELEASE_NOTES_VALUE" \
BACKEND_SBOM_SHA256="$BACKEND_SBOM_SHA256" FRONTEND_SBOM_SHA256="$FRONTEND_SBOM_SHA256" \ BACKEND_SBOM_SHA256="$BACKEND_SBOM_SHA256" FRONTEND_SBOM_SHA256="$FRONTEND_SBOM_SHA256" \
BACKEND_BUILD_VERSION="$BACKEND_BUILD_VERSION" FRONTEND_BUILD_VERSION="$FRONTEND_BUILD_VERSION" \ BACKEND_BUILD_VERSION="$BACKEND_BUILD_VERSION" FRONTEND_BUILD_VERSION="$FRONTEND_BUILD_VERSION" \
INSTALLER_SHA256="$INSTALLER_SHA256" PURGER_SHA256="$PURGER_SHA256" \ INSTALLER_SHA256="$INSTALLER_SHA256" PURGER_SHA256="$PURGER_SHA256" \
@@ -179,6 +181,7 @@ const manifest = {
version: process.env.VERSION, version: process.env.VERSION,
artifact: process.env.ARTIFACT, artifact: process.env.ARTIFACT,
sha256: process.env.SHA256, sha256: process.env.SHA256,
artifactSizeBytes: Number(process.env.ARTIFACT_SIZE_BYTES),
publishedAt: new Date().toISOString(), publishedAt: new Date().toISOString(),
minimumJava: 17, minimumJava: 17,
source: { source: {
+6 -2
View File
@@ -319,8 +319,12 @@ grep -Fqx 'StartLimitBurst=3' "$ROOT/deploy/systemd/kaidi-finance.service" \
|| fail 'application service no longer has a bounded restart burst' || fail 'application service no longer has a bounded restart burst'
grep -Fqx 'Restart=no' "$ROOT/deploy/systemd/kaidi-update.service" \ grep -Fqx 'Restart=no' "$ROOT/deploy/systemd/kaidi-update.service" \
|| fail 'update service can automatically repeat a failed switching transaction' || fail 'update service can automatically repeat a failed switching transaction'
! grep -Fq '/var/lib/kaidi-update/processing' "$ROOT/deploy/systemd/kaidi-update.path" \ grep -Fq -- '-/www/wwwroot/kaidi' "$ROOT/deploy/systemd/kaidi-update.service" \
|| fail 'update path can automatically repeat a claimed switching transaction' || fail 'update service requires the Baota application path on a systemd-only installation'
grep -Fqx 'PathExists=/var/lib/kaidi-update/processing/request.json' "$ROOT/deploy/systemd/kaidi-update.path" \
|| fail 'update path does not resume an interrupted claimed request'
grep -Fqx 'PathExists=/var/lib/kaidi-update/transactions/active' "$ROOT/deploy/systemd/kaidi-update.path" \
|| fail 'update path does not resume an interrupted switching transaction'
# shellcheck disable=SC2016 # Match literal installer source. # shellcheck disable=SC2016 # Match literal installer source.
grep -Fq '[ "$actual_sha256" = "$java_sha256" ]' "$ROOT/deploy/install.sh" \ grep -Fq '[ "$actual_sha256" = "$java_sha256" ]' "$ROOT/deploy/install.sh" \
|| fail 'installer no longer verifies the Java runtime SHA-256' || fail 'installer no longer verifies the Java runtime SHA-256'
+8
View File
@@ -83,5 +83,13 @@ grep -Fq 'KAIDI_PURGE_CONFIRM=$REQUIRED_CONFIRMATION' "$ROOT/deploy/purge.sh" \
|| fail 'destructive removal no longer requires explicit confirmation' || fail 'destructive removal no longer requires explicit confirmation'
grep -Fq 'External MySQL data and reverse-proxy configuration will not be modified' "$ROOT/deploy/purge.sh" \ grep -Fq 'External MySQL data and reverse-proxy configuration will not be modified' "$ROOT/deploy/purge.sh" \
|| fail 'purge boundary is no longer explicit' || fail 'purge boundary is no longer explicit'
# shellcheck disable=SC2016 # Match literal service-account cleanup calls.
grep -Fq 'terminate_uid_processes "$service_uid"' "$ROOT/deploy/purge.sh" \
|| fail 'dedicated service-account processes are not terminated before account removal'
# shellcheck disable=SC2016 # Match literal forced account removal.
grep -Fq 'userdel --force "$SERVICE_USER"' "$ROOT/deploy/purge.sh" \
|| fail 'dedicated service-account removal is not resilient to a restarting panel process'
grep -Fq '/etc/systemd/system/kaidi-update.service.d' "$ROOT/deploy/purge.sh" \
|| fail 'updater systemd drop-ins are not removed'
printf 'Local purge and recovery fixture passed\n' printf 'Local purge and recovery fixture passed\n'
+140 -10
View File
@@ -26,18 +26,35 @@ for version in 01.2.3 1.02.3 1.2.03 1.2.3-01 1.2.3-alpha..1; do
done done
missing_service_user="kaidi-fixture-missing-$$" missing_service_user="kaidi-fixture-missing-$$"
mkdir -p "$WORK/bootstrap/app" "$WORK/bootstrap/state/inbox" \
"$WORK/bootstrap/state/processing" "$WORK/bootstrap/state/failed" "$WORK/bootstrap/log" \
"$WORK/bootstrap/bin"
cat > "$WORK/bootstrap/bin/flock" <<'SH'
#!/bin/sh
exit 0
SH
chmod 0755 "$WORK/bootstrap/bin/flock"
jq -n \
'{action:"DOWNLOAD",version:"1.0.0-preview.2",reason:"bootstrap fixture"}' \
> "$WORK/bootstrap/state/inbox/request.json"
if KAIDI_APP_ROOT="$WORK/bootstrap/app" \ if KAIDI_APP_ROOT="$WORK/bootstrap/app" \
KAIDI_UPDATE_STATE_ROOT="$WORK/bootstrap/state" \ KAIDI_UPDATE_STATE_ROOT="$WORK/bootstrap/state" \
KAIDI_LOG_ROOT="$WORK/bootstrap/log" \ KAIDI_LOG_ROOT="$WORK/bootstrap/log" \
KAIDI_SERVICE_USER="$missing_service_user" \ KAIDI_SERVICE_USER="$missing_service_user" \
KAIDI_SERVICE_GROUP="$missing_service_user" \ KAIDI_SERVICE_GROUP="$missing_service_user" \
PATH="$WORK/bootstrap/bin:$PATH" \
sh "$ROOT/deploy/update.sh" > "$WORK/bootstrap.log" 2>&1; then sh "$ROOT/deploy/update.sh" > "$WORK/bootstrap.log" 2>&1; then
fail 'updater accepted a missing service identity during bootstrap' fail 'updater accepted a missing service identity during bootstrap'
fi fi
grep -Fq "Service user $missing_service_user is missing" "$WORK/bootstrap.log" \ grep -Fq "Service user $missing_service_user is missing" "$WORK/bootstrap.log" \
|| fail 'updater bootstrap failure did not preserve its diagnostic' || fail 'updater bootstrap failure did not preserve its diagnostic'
! grep -Eq 'No such file|nonexistent directory|cannot create' "$WORK/bootstrap.log" \ [ "$(jq -r '.state' "$WORK/bootstrap/state/status.json")" = FAILED ] \
|| fail 'updater bootstrap failure was masked by an unavailable status directory' || fail 'updater bootstrap failure did not persist FAILED'
[ ! -e "$WORK/bootstrap/state/inbox/request.json" ] \
&& [ ! -e "$WORK/bootstrap/state/processing/request.json" ] \
|| fail 'updater bootstrap failure left a request permanently queued'
find "$WORK/bootstrap/state/failed" -type f -name 'request-*.json' -print -quit | grep -q . \
|| fail 'updater bootstrap failure did not archive the claimed request'
write_mock_commands() { write_mock_commands() {
local mock_bin=$1 local mock_bin=$1
@@ -48,10 +65,14 @@ write_mock_commands() {
output= output=
url= url=
header_file= header_file=
write_out=
http_status=200
printf '%s\n' "$*" >> "${MOCK_CURL_LOG:-/dev/null}" printf '%s\n' "$*" >> "${MOCK_CURL_LOG:-/dev/null}"
while [ "$#" -gt 0 ]; do while [ "$#" -gt 0 ]; do
case "$1" in case "$1" in
-o) shift; output=$1 ;; -o|--output) shift; output=$1 ;;
--write-out) shift; write_out=$1 ;;
--connect-timeout|--max-time) shift ;;
--header|-H) --header|-H)
shift shift
case "${1:-}" in @*) header_file=${1#@} ;; esac case "${1:-}" in @*) header_file=${1#@} ;; esac
@@ -73,6 +94,26 @@ esac
if [ -n "$output" ]; then if [ -n "$output" ]; then
if [ -n "${MOCK_RELEASE_API_URL:-}" ] && [ "$url" = "$MOCK_RELEASE_API_URL" ]; then if [ -n "${MOCK_RELEASE_API_URL:-}" ] && [ "$url" = "$MOCK_RELEASE_API_URL" ]; then
cp "$FIXTURE_RELEASE_ROOT/release-api.json" "$output" cp "$FIXTURE_RELEASE_ROOT/release-api.json" "$output"
elif [ "$url" = "${KAIDI_HEALTH_URL:-http://127.0.0.1:18080/actuator/health}" ]; then
health_ok=false
case "${MOCK_HEALTH:-success}" in
success) health_ok=true ;;
fail-new)
[ "$(cat "$MOCK_APP_ROOT/current/VERSION" 2>/dev/null)" = '1.0.0-preview.1' ] && health_ok=true
;;
fail-after-first)
health_count=$(cat "$MOCK_APP_ROOT/health-count" 2>/dev/null || printf 0)
health_count=$((health_count + 1))
printf '%s\n' "$health_count" > "$MOCK_APP_ROOT/health-count"
[ "$health_count" -eq 1 ] && health_ok=true
;;
esac
if [ "$health_ok" = true ]; then
printf '{"status":"UP"}\n' > "$output"
else
printf '{"status":"DOWN"}\n' > "$output"
http_status=503
fi
elif [ "$url" = "${KAIDI_APP_INDEX_URL:-http://127.0.0.1:18080/}" ]; then elif [ "$url" = "${KAIDI_APP_INDEX_URL:-http://127.0.0.1:18080/}" ]; then
cp "$MOCK_APP_ROOT/current/public/index.html" "$output" cp "$MOCK_APP_ROOT/current/public/index.html" "$output"
else else
@@ -87,6 +128,7 @@ elif [ "${MOCK_HEALTH:-success}" = fail-new ] \
else else
exit 22 exit 22
fi fi
[ -z "$write_out" ] || printf '%s' "$http_status"
SH SH
cat > "$mock_bin/systemctl" <<'SH' cat > "$mock_bin/systemctl" <<'SH'
@@ -99,6 +141,11 @@ SH
cat > "$mock_bin/flock" <<'SH' cat > "$mock_bin/flock" <<'SH'
#!/bin/sh #!/bin/sh
exit 0 exit 0
SH
cat > "$mock_bin/setsid" <<'SH'
#!/bin/sh
exec "$@"
SH SH
cat > "$mock_bin/systemd-analyze" <<'SH' cat > "$mock_bin/systemd-analyze" <<'SH'
@@ -194,10 +241,12 @@ build_release() {
local artifact="kaidi-finance-$version.tar.gz" local artifact="kaidi-finance-$version.tar.gz"
COPYFILE_DISABLE=1 tar -czf "$fixture/release/$artifact" -C "$stage" . COPYFILE_DISABLE=1 tar -czf "$fixture/release/$artifact" -C "$stage" .
local sha local sha size
sha=$($REAL_OPENSSL dgst -sha256 "$fixture/release/$artifact" | awk '{print $NF}') sha=$($REAL_OPENSSL dgst -sha256 "$fixture/release/$artifact" | awk '{print $NF}')
jq -n --arg version "$version" --arg artifact "$artifact" --arg sha "$sha" \ size=$(wc -c < "$fixture/release/$artifact" | tr -d '[:space:]')
'{version:$version,artifact:$artifact,sha256:$sha,publishedAt:"2026-08-16T00:00:00Z",releaseNotes:"fixture"}' \ jq -n --arg version "$version" --arg artifact "$artifact" --arg sha "$sha" --argjson size "$size" \
'{version:$version,artifact:$artifact,sha256:$sha,artifactSizeBytes:$size,
publishedAt:"2026-08-16T00:00:00Z",releaseNotes:"fixture"}' \
> "$fixture/release/release-manifest.json" > "$fixture/release/release-manifest.json"
"$REAL_OPENSSL" dgst -sha256 -sign "$fixture/private.pem" \ "$REAL_OPENSSL" dgst -sha256 -sign "$fixture/private.pem" \
-out "$fixture/release/release-manifest.sig" "$fixture/release/release-manifest.json" -out "$fixture/release/release-manifest.sig" "$fixture/release/release-manifest.json"
@@ -252,6 +301,7 @@ write_request() {
download_and_prepare_install() { download_and_prepare_install() {
local fixture=$1 local fixture=$1
local version=$2 local version=$2
truncate -s 0 "$fixture/systemctl.log"
run_update "$fixture" success run_update "$fixture" success
[ "$(jq -r '.state' "$fixture/state/status.json")" = READY ] \ [ "$(jq -r '.state' "$fixture/state/status.json")" = READY ] \
|| fail 'download phase did not persist READY' || fail 'download phase did not persist READY'
@@ -259,6 +309,16 @@ download_and_prepare_install() {
|| fail 'download phase changed the active application' || fail 'download phase changed the active application'
[ -s "$fixture/state/cache/$version/release.tar.gz" ] \ [ -s "$fixture/state/cache/$version/release.tar.gz" ] \
|| fail 'download phase did not persist the verified artifact cache' || fail 'download phase did not persist the verified artifact cache'
[ "$(jq -r '.downloadPercent' "$fixture/state/status.json")" -eq 100 ] \
|| fail 'download phase did not persist 100 percent progress'
[ "$(jq -r '.totalBytes' "$fixture/state/status.json")" -gt 0 ] \
|| fail 'download phase did not persist artifact bytes'
[ "$(jq -r '.bytesPerSecond' "$fixture/state/status.json")" -gt 0 ] \
|| fail 'download phase did not persist a measured transfer speed'
grep -Fq '"stage":"DOWNLOADING"' "$fixture/state/events.jsonl" \
|| fail 'download phase did not persist structured runtime events'
! grep -Eq '^(start|restart|stop) kaidi-finance.service$' "$fixture/systemctl.log" \
|| fail 'download phase changed the application service'
write_request "$fixture" "$version" INSTALL write_request "$fixture" "$version" INSTALL
} }
@@ -390,7 +450,7 @@ assert_identical_systemd_operations_case() {
prepare_installation "$fixture" "$version" prepare_installation "$fixture" "$version"
download_and_prepare_install "$fixture" "$version" download_and_prepare_install "$fixture" "$version"
: > "$fixture/systemctl.log" truncate -s 0 "$fixture/systemctl.log"
run_update "$fixture" success run_update "$fixture" success
[ "$(readlink "$fixture/app/current")" = "$fixture/app/releases/$version" ] \ [ "$(readlink "$fixture/app/current")" = "$fixture/app/releases/$version" ] \
|| fail 'identical systemd case did not activate the new application' || fail 'identical systemd case did not activate the new application'
@@ -457,17 +517,33 @@ assert_incomplete_rollback_requires_manual_recovery_case() {
prepare_installation "$fixture" "$version" prepare_installation "$fixture" "$version"
download_and_prepare_install "$fixture" "$version" download_and_prepare_install "$fixture" "$version"
if run_update "$fixture" fail > "$fixture/update.log" 2>&1; then if run_update "$fixture" fail-after-first > "$fixture/update.log" 2>&1; then
fail 'incomplete rollback case unexpectedly succeeded' fail 'incomplete rollback case unexpectedly succeeded'
fi fi
grep -Fq 'manual recovery is required' "$fixture/update.log" \ grep -Fq 'manual recovery is required' "$fixture/update.log" \
|| fail 'incomplete rollback case did not require explicit recovery' || fail 'incomplete rollback case did not require explicit recovery'
[ ! -e "$fixture/state/processing/request.json" ] \ [ ! -e "$fixture/state/processing/request.json" ] \
|| fail 'incomplete rollback case left an automatically retriggered processing request' || fail 'incomplete rollback case left an automatically retriggered processing request'
[ -d "$fixture/state/transactions/active" ] \ [ ! -e "$fixture/state/transactions/active" ] \
|| fail 'incomplete rollback case did not preserve transaction evidence' || fail 'incomplete rollback case left transaction evidence on the automatic recovery path'
[ -d "$fixture/state/transactions/recovery-required" ] \
|| fail 'incomplete rollback case did not quarantine transaction evidence'
[ "$(jq -r '.state' "$fixture/state/status.json")" = RECOVERY_REQUIRED ] \
|| fail 'incomplete rollback case did not lock the updater for recovery'
find "$fixture/state/failed" -type f -name 'request-*.json' -print -quit | grep -q . \ find "$fixture/state/failed" -type f -name 'request-*.json' -print -quit | grep -q . \
|| fail 'incomplete rollback case did not archive its claimed request' || fail 'incomplete rollback case did not archive its claimed request'
truncate -s 0 "$fixture/systemctl.log"
write_request "$fixture" "$version" DOWNLOAD
if run_update "$fixture" success > "$fixture/retry.log" 2>&1; then
fail 'recovery-locked updater accepted a new download request'
fi
[ "$(jq -r '.state' "$fixture/state/status.json")" = RECOVERY_REQUIRED ] \
|| fail 'recovery-locked updater replaced the manual recovery status'
! grep -Eq '^(start|restart|stop) kaidi-finance.service$' "$fixture/systemctl.log" \
|| fail 'recovery-locked download request changed the application service'
[ ! -e "$fixture/state/inbox/request.json" ] && [ ! -e "$fixture/state/processing/request.json" ] \
|| fail 'recovery-locked updater left a request on an automatic trigger path'
} }
assert_download_failure_case() { assert_download_failure_case() {
@@ -509,6 +585,58 @@ assert_database_failure_case() {
|| fail 'database failure did not persist FAILED' || fail 'database failure did not persist FAILED'
} }
assert_unhealthy_baseline_blocks_restart_case() {
local fixture="$WORK/unhealthy-baseline"
local version='1.0.0-preview.2'
mkdir -p "$fixture"
write_mock_commands "$fixture/mock-bin"
build_release "$fixture" "$version"
prepare_installation "$fixture" "$version"
download_and_prepare_install "$fixture" "$version"
truncate -s 0 "$fixture/systemctl.log"
if run_update "$fixture" fail > "$fixture/update.log" 2>&1; then
fail 'unhealthy baseline unexpectedly reached installation'
fi
grep -Fq 'Current release preflight failed' "$fixture/update.log" \
|| fail 'unhealthy baseline did not preserve its preflight diagnostic'
! grep -Eq '^(start|restart|stop) kaidi-finance.service$' "$fixture/systemctl.log" \
|| fail 'unhealthy baseline restarted the application'
[ "$(readlink "$fixture/app/current")" = "$fixture/app/releases/1.0.0-preview.1" ] \
|| fail 'unhealthy baseline changed the active release'
[ ! -e "$fixture/state/transactions/active" ] \
|| fail 'unhealthy baseline created a switching transaction'
}
assert_invalid_database_url_blocks_restart_case() {
local fixture="$WORK/invalid-database-url"
local version='1.0.0-preview.2'
mkdir -p "$fixture"
write_mock_commands "$fixture/mock-bin"
build_release "$fixture" "$version"
prepare_installation "$fixture" "$version"
download_and_prepare_install "$fixture" "$version"
cat > "$fixture/runtime.env" <<'EOF'
DB_URL="jdbc:mysql://"
KAIDI_DB_HOST="127.0.0.1"
KAIDI_DB_PORT="3306"
KAIDI_DB_NAME="kaidi_finance"
KAIDI_DB_USERNAME="kaidi"
KAIDI_DB_PASSWORD="fixture"
EOF
truncate -s 0 "$fixture/systemctl.log"
if run_update "$fixture" success > "$fixture/update.log" 2>&1; then
fail 'invalid database URL unexpectedly reached installation'
fi
grep -Fq 'DB_URL does not match the configured MySQL host, port, and database' "$fixture/update.log" \
|| fail 'structurally invalid JDBC URL did not preserve its diagnostic'
! grep -q '^restart kaidi-finance.service$' "$fixture/systemctl.log" \
|| fail 'invalid database URL restarted the application'
[ "$(readlink "$fixture/app/current")" = "$fixture/app/releases/1.0.0-preview.1" ] \
|| fail 'invalid database URL changed the active release'
}
assert_symlink_request_rejected() { assert_symlink_request_rejected() {
local fixture="$WORK/symlink-request" local fixture="$WORK/symlink-request"
local version='1.0.0-preview.2' local version='1.0.0-preview.2'
@@ -560,6 +688,8 @@ assert_rollback_case
assert_incomplete_rollback_requires_manual_recovery_case assert_incomplete_rollback_requires_manual_recovery_case
assert_download_failure_case assert_download_failure_case
assert_database_failure_case assert_database_failure_case
assert_unhealthy_baseline_blocks_restart_case
assert_invalid_database_url_blocks_restart_case
assert_symlink_request_rejected assert_symlink_request_rejected
assert_install_without_verified_cache_rejected assert_install_without_verified_cache_rejected
assert_private_gitea_release_case assert_private_gitea_release_case
+4
View File
@@ -56,6 +56,10 @@ EXPECTED_ARTIFACT_SHA256=$(jq -er \
release-manifest.json) release-manifest.json)
[ "$(sha256_file "$ARTIFACT")" = "$EXPECTED_ARTIFACT_SHA256" ] \ [ "$(sha256_file "$ARTIFACT")" = "$EXPECTED_ARTIFACT_SHA256" ] \
|| { printf 'Release artifact digest does not match the signed manifest\n' >&2; exit 1; } || { printf 'Release artifact digest does not match the signed manifest\n' >&2; exit 1; }
EXPECTED_ARTIFACT_SIZE=$(jq -er '.artifactSizeBytes | numbers | floor | select(. > 0)' \
release-manifest.json)
[ "$(wc -c < "$ARTIFACT" | tr -d '[:space:]')" -eq "$EXPECTED_ARTIFACT_SIZE" ] \
|| { printf 'Release artifact size does not match the signed manifest\n' >&2; exit 1; }
[ "$(jq '.sboms | length' release-manifest.json)" -eq 2 ] \ [ "$(jq '.sboms | length' release-manifest.json)" -eq 2 ] \
|| { printf 'Release manifest must bind two SBOMs\n' >&2; exit 1; } || { printf 'Release manifest must bind two SBOMs\n' >&2; exit 1; }
jq -e --arg version "$VERSION" \ jq -e --arg version "$VERSION" \