Files
crawler-plugin/backend-java/src/main/java/com/nanri/aiimage/config/InstanceMetadata.java
T
huangzd1997 7bb03466b0 fix(任务): 开机自回收改以本进程启动时刻为界,发版不再蚕食结果文件作业的重试次数
原判据是 now-max(60,staleSeconds),但 ApplicationReadyEvent 只在重启后几秒响一次,
那时遗留行的心跳也只停了几秒,条件结构上永不成立——线上"实例重启,作业已重新排队"累计 0 条。
遗骸改由 stuck 扫描按 +1 重试处理(今天 A 发了 7 版、重试预算只有 5),
20833 已被吃掉一次,20836/任务29475 就是被这条链判成"已达到最大重试次数"的。
2026-09-28 15:59:47 +08:00

87 lines
3.1 KiB
Java

package com.nanri.aiimage.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
@Slf4j
@Component
public class InstanceMetadata {
private final String instanceId;
private final String hostname;
private final String source;
private final boolean stable;
/**
* 本进程的启动时刻。开机自回收用它当界:owner=本机且 status=RUNNING 的行若
* {@code updated_at} 早于这一刻,只可能是上一个进程留下的遗骸,不可能是本进程在跑的。
*/
private final LocalDateTime startedAt;
public InstanceMetadata(@Value("${aiimage.instance-id:}") String configuredInstanceId) {
this.startedAt = LocalDateTime.ofInstant(
Instant.ofEpochMilli(ManagementFactory.getRuntimeMXBean().getStartTime()),
ZoneId.systemDefault());
this.hostname = resolveHostname();
String normalizedConfiguredInstanceId = configuredInstanceId == null ? "" : configuredInstanceId.trim();
if (!normalizedConfiguredInstanceId.isBlank()) {
this.instanceId = normalizedConfiguredInstanceId;
this.source = "configured";
this.stable = true;
log.info("[instance] resolved instanceId={} source={} hostname={} continuityRisk=LOW",
this.instanceId, this.source, this.hostname);
} else {
this.instanceId = this.hostname;
this.source = detectFallbackSource(this.hostname);
this.stable = false;
log.warn("[instance] aiimage.instance-id is not configured, falling back to {}={} as instanceId. "
+ "This may change after restart/redeploy and break task owner continuity. "
+ "Set AIIMAGE_INSTANCE_ID in 1Panel/Docker env, or set -Daiimage.instance-id=<stable-id> in IDEA/local startup.",
this.source, this.hostname);
}
}
public String getInstanceId() {
return instanceId;
}
public String getHostname() {
return hostname;
}
public String getSource() {
return source;
}
public boolean isStable() {
return stable;
}
public LocalDateTime getStartedAt() {
return startedAt;
}
private static String resolveHostname() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (Exception ignored) {
String envHostname = System.getenv("HOSTNAME");
return (envHostname == null || envHostname.isBlank()) ? "unknown-host" : envHostname;
}
}
private static String detectFallbackSource(String hostname) {
String envHostname = System.getenv("HOSTNAME");
if (envHostname != null && !envHostname.isBlank() && envHostname.equalsIgnoreCase(hostname)) {
return "env.HOSTNAME";
}
return "os.hostname";
}
}