feat: 交付本地可运行 V1 候选版
实现初始化、单管理员认证、NapCat 被动接收、消息查询、媒体与发送闭环,补齐前端、自动化测试及同步文档。
This commit is contained in:
@@ -0,0 +1,250 @@
|
||||
package com.qlinker.init;
|
||||
|
||||
import com.qlinker.config.QLinkerProperties;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.jdbc.datasource.DriverManagerDataSource;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Timestamp;
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
/**
|
||||
* 实例初始化编排(架构设计 13.3、AGENTS.md 12 章)。
|
||||
*
|
||||
* <p>职责:确定并持久化资源身份、按需创建隔离数据库与 bucket、执行 Flyway 迁移、
|
||||
* 双向校验身份与真实资源是否一致。任何不一致都进入 RECOVERY_REQUIRED 并阻断业务,
|
||||
* 绝不自动新建一套空资源继续运行,以免历史数据被遗弃或产生数据分裂。</p>
|
||||
*
|
||||
* <p>每一步完成后立即落盘阶段状态,使进程中断后的重启能够判断已完成到哪一步,
|
||||
* 而不是重复执行可能产生破坏性结果的操作(AGENTS.md 12.3)。</p>
|
||||
*/
|
||||
public class BootstrapCoordinator {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(BootstrapCoordinator.class);
|
||||
|
||||
private final QLinkerProperties properties;
|
||||
private final InstanceStateStore stateStore;
|
||||
private final DatabaseProvisioner databaseProvisioner;
|
||||
private final BucketProvisioner bucketProvisioner;
|
||||
private final SchemaMigrator schemaMigrator;
|
||||
private final java.security.SecureRandom random = new java.security.SecureRandom();
|
||||
|
||||
private final AtomicReference<InstanceIdentity> identity = new AtomicReference<>();
|
||||
private final AtomicReference<String> blockedReason = new AtomicReference<>();
|
||||
|
||||
public BootstrapCoordinator(QLinkerProperties properties,
|
||||
InstanceStateStore stateStore,
|
||||
DatabaseProvisioner databaseProvisioner,
|
||||
BucketProvisioner bucketProvisioner,
|
||||
SchemaMigrator schemaMigrator) {
|
||||
this.properties = properties;
|
||||
this.stateStore = stateStore;
|
||||
this.databaseProvisioner = databaseProvisioner;
|
||||
this.bucketProvisioner = bucketProvisioner;
|
||||
this.schemaMigrator = schemaMigrator;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保证实例处于可服务状态。返回已确认的资源身份;无法确认时抛出异常并保留阻断原因。
|
||||
*/
|
||||
public synchronized InstanceIdentity ensureReady() {
|
||||
InstanceIdentity current = identity.get();
|
||||
if (current != null && current.stage() == InstanceIdentity.Stage.READY) {
|
||||
return current;
|
||||
}
|
||||
try {
|
||||
InstanceIdentity resolved = doEnsureReady();
|
||||
identity.set(resolved);
|
||||
blockedReason.set(null);
|
||||
return resolved;
|
||||
} catch (InstanceBlocked e) {
|
||||
blockedReason.set(e.getMessage());
|
||||
identity.set(new InstanceIdentity(null, null, null, InstanceIdentity.Stage.RECOVERY_REQUIRED, null));
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private InstanceIdentity doEnsureReady() {
|
||||
Optional<InstanceStateStore.InstanceState> stored = stateStore.read();
|
||||
if (stored.isEmpty()) {
|
||||
return firstRun();
|
||||
}
|
||||
return resume(stored.get());
|
||||
}
|
||||
|
||||
private InstanceIdentity firstRun() {
|
||||
if (!properties.getInstance().isBootstrapEnabled()) {
|
||||
throw new InstanceBlocked("实例尚未初始化,且 qlinker.instance.bootstrap-enabled=false 禁止自动初始化。"
|
||||
+ "请在部署环境准备隔离数据库与 bucket 后写入状态文件 " + stateStore.stateFile());
|
||||
}
|
||||
int maxAttempts = Math.max(1, properties.getInstance().getMaxCreateAttempts());
|
||||
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
|
||||
String randomId = ResourceNames.randomId(random, properties.getInstance().getRandomIdLength());
|
||||
String databaseName = ResourceNames.databaseName(randomId);
|
||||
String bucketName = ResourceNames.bucketName(randomId);
|
||||
if (databaseProvisioner.databaseExists(databaseName) || bucketProvisioner.bucketExists(bucketName)) {
|
||||
log.warn("随机资源名称冲突,重新生成 attempt={} database={}", attempt, databaseName);
|
||||
continue;
|
||||
}
|
||||
String instanceUid = "inst_" + randomId;
|
||||
// 先落盘名称再创建资源:即使创建过程中进程被中断,重启时也能核实是否已经创建,而不是换一套新名字。
|
||||
persist(instanceUid, databaseName, bucketName, InstanceIdentity.Stage.PLANNED, null);
|
||||
|
||||
if (!databaseProvisioner.databaseExists(databaseName)) {
|
||||
databaseProvisioner.createDatabase(databaseName);
|
||||
}
|
||||
persist(instanceUid, databaseName, bucketName, InstanceIdentity.Stage.DATABASE_CREATED, null);
|
||||
|
||||
if (!bucketProvisioner.bucketExists(bucketName)) {
|
||||
bucketProvisioner.createBucket(bucketName);
|
||||
}
|
||||
persist(instanceUid, databaseName, bucketName, InstanceIdentity.Stage.BUCKET_CREATED, null);
|
||||
|
||||
String version = schemaMigrator.migrate(databaseBusinessDataSource(databaseName));
|
||||
persist(instanceUid, databaseName, bucketName, InstanceIdentity.Stage.SCHEMA_MIGRATED, version);
|
||||
|
||||
recordInstanceRow(instanceUid, databaseName, bucketName, version);
|
||||
InstanceIdentity ready = persist(instanceUid, databaseName, bucketName, InstanceIdentity.Stage.READY, version);
|
||||
log.info("实例初始化完成 instanceUid={} database={} bucket={} schema={}",
|
||||
instanceUid, databaseName, bucketName, version);
|
||||
return ready;
|
||||
}
|
||||
throw new InstanceBlocked("连续 " + maxAttempts + " 次生成的随机资源名称均与已有资源冲突,请检查命名冲突或加大随机长度");
|
||||
}
|
||||
|
||||
private InstanceIdentity resume(InstanceStateStore.InstanceState state) {
|
||||
InstanceIdentity current = state.toIdentity();
|
||||
if (current.stage().isBlocked()) {
|
||||
throw new InstanceBlocked("实例状态文件处于 RECOVERY_REQUIRED,需要人工确认资源身份后修复状态文件");
|
||||
}
|
||||
if (!ResourceNames.isValidDatabaseName(current.databaseName()) || !ResourceNames.isValidBucketName(current.bucketName())) {
|
||||
throw new InstanceBlocked("实例状态文件中的资源名称不满足命名规则,疑似被篡改或损坏");
|
||||
}
|
||||
|
||||
InstanceIdentity verified = current;
|
||||
boolean dbExists = safe(() -> databaseProvisioner.databaseExists(verified.databaseName()), "数据库可达性");
|
||||
if (!dbExists) {
|
||||
throw new InstanceBlocked("状态文件记录的业务数据库不存在或不可访问 database=" + current.databaseName()
|
||||
+ ";已拒绝自动创建新资源,请确认数据库是否被删除或连接配置是否变更");
|
||||
}
|
||||
boolean bucketExists = safe(() -> bucketProvisioner.bucketExists(verified.bucketName()), "bucket 可达性");
|
||||
if (!bucketExists) {
|
||||
throw new InstanceBlocked("状态文件记录的 bucket 不存在或不可访问 bucket=" + current.bucketName()
|
||||
+ ";已拒绝自动创建新资源,请确认 bucket 是否被删除或凭据是否变更");
|
||||
}
|
||||
|
||||
DataSource ds = databaseBusinessDataSource(current.databaseName());
|
||||
if (!current.stage().atLeast(InstanceIdentity.Stage.SCHEMA_MIGRATED)) {
|
||||
String version = schemaMigrator.migrate(ds);
|
||||
current = persist(current.instanceUid(), current.databaseName(), current.bucketName(),
|
||||
InstanceIdentity.Stage.SCHEMA_MIGRATED, version);
|
||||
}
|
||||
String version = current.stage().atLeast(InstanceIdentity.Stage.SCHEMA_MIGRATED)
|
||||
? current.schemaVersion()
|
||||
: schemaMigrator.currentVersion(ds);
|
||||
|
||||
verifyInstanceRow(ds, current, version);
|
||||
if (current.stage() != InstanceIdentity.Stage.READY) {
|
||||
current = persist(current.instanceUid(), current.databaseName(), current.bucketName(),
|
||||
InstanceIdentity.Stage.READY, version);
|
||||
}
|
||||
log.info("实例身份复用成功 instanceUid={} database={} bucket={}",
|
||||
current.instanceUid(), current.databaseName(), current.bucketName());
|
||||
return current;
|
||||
}
|
||||
|
||||
/** system_instance 记录与状态文件必须互相印证,任一侧缺失或不同即视为身份异常。 */
|
||||
private void verifyInstanceRow(DataSource ds, InstanceIdentity current, String version) {
|
||||
String sql = "SELECT instance_uid, database_name, bucket_name FROM system_instance WHERE instance_uid = ?";
|
||||
try (Connection c = ds.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, current.instanceUid());
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
if (!rs.next()) {
|
||||
recordInstanceRow(current.instanceUid(), current.databaseName(), current.bucketName(), version);
|
||||
return;
|
||||
}
|
||||
String db = rs.getString("database_name");
|
||||
String bucket = rs.getString("bucket_name");
|
||||
if (!current.databaseName().equals(db) || !current.bucketName().equals(bucket)) {
|
||||
throw new InstanceBlocked("system_instance 记录与状态文件不一致:数据库记录 database=" + db + ", bucket=" + bucket
|
||||
+ ";状态文件 database=" + current.databaseName() + ", bucket=" + current.bucketName()
|
||||
+ "。已拒绝自动改写,请人工确认哪一侧为真实资源");
|
||||
}
|
||||
}
|
||||
} catch (InstanceBlocked e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new InstanceBlocked("无法读取 system_instance 记录以确认资源身份:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void recordInstanceRow(String instanceUid, String databaseName, String bucketName, String version) {
|
||||
String sql = "INSERT INTO system_instance (instance_uid, instance_name, database_name, bucket_name, "
|
||||
+ "init_status, schema_version, created_at, updated_at) VALUES (?, ?, ?, ?, 'READY', ?, ?, ?)";
|
||||
Timestamp now = Timestamp.from(Instant.now());
|
||||
try (Connection c = databaseBusinessDataSource(databaseName).getConnection();
|
||||
PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, instanceUid);
|
||||
ps.setString(2, "QLinker " + instanceUid);
|
||||
ps.setString(3, databaseName);
|
||||
ps.setString(4, bucketName);
|
||||
ps.setString(5, version);
|
||||
ps.setTimestamp(6, now);
|
||||
ps.setTimestamp(7, now);
|
||||
ps.executeUpdate();
|
||||
} catch (Exception e) {
|
||||
throw new InstanceBlocked("无法写入 system_instance 资源身份记录:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private DataSource databaseBusinessDataSource(String databaseName) {
|
||||
DriverManagerDataSource ds = new DriverManagerDataSource();
|
||||
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
|
||||
ds.setUrl(databaseProvisioner.businessJdbcUrl(databaseName));
|
||||
ds.setUsername(properties.getInstance().getMysqlUser());
|
||||
ds.setPassword(properties.getInstance().getMysqlPassword());
|
||||
return ds;
|
||||
}
|
||||
|
||||
private InstanceIdentity persist(String instanceUid, String databaseName, String bucketName,
|
||||
InstanceIdentity.Stage stage, String version) {
|
||||
stateStore.write(new InstanceStateStore.InstanceState(instanceUid, databaseName, bucketName, stage, version));
|
||||
return new InstanceIdentity(instanceUid, databaseName, bucketName, stage, version);
|
||||
}
|
||||
|
||||
private boolean safe(java.util.function.BooleanSupplier check, String what) {
|
||||
try {
|
||||
return check.getAsBoolean();
|
||||
} catch (Exception e) {
|
||||
throw new InstanceBlocked("无法确认" + what + ":" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** 供状态接口读取的只读快照,不触发初始化。 */
|
||||
public Optional<InstanceIdentity> peek() {
|
||||
return Optional.ofNullable(identity.get());
|
||||
}
|
||||
|
||||
public Optional<String> blockedReason() {
|
||||
return Optional.ofNullable(blockedReason.get());
|
||||
}
|
||||
|
||||
/** 测试与本地开发使用:清空内存快照,强制下一次访问重新核验。 */
|
||||
public void resetForTest() {
|
||||
identity.set(null);
|
||||
blockedReason.set(null);
|
||||
}
|
||||
|
||||
/** 资源身份异常:需要人工介入,禁止自动新建资源。 */
|
||||
public static class InstanceBlocked extends RuntimeException {
|
||||
public InstanceBlocked(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package com.qlinker.init;
|
||||
|
||||
import com.qlinker.security.AuthService;
|
||||
import com.qlinker.security.CryptoService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* 启动后的初始化收尾(AGENTS.md 12.1、12.3)。
|
||||
*
|
||||
* <p>引导令牌只在「尚无管理员且从未签发过令牌」时生成一次,明文只在本进程日志输出一次,
|
||||
* 数据库仅保存哈希。已初始化的实例重启不会重新签发,也不会重新创建任何资源。</p>
|
||||
*/
|
||||
public class BootstrapRunner implements ApplicationRunner {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(BootstrapRunner.class);
|
||||
|
||||
private static final Duration BOOTSTRAP_TTL = Duration.ofHours(24);
|
||||
|
||||
private final BootstrapCoordinator coordinator;
|
||||
private final AuthService auth;
|
||||
private final CryptoService crypto;
|
||||
private final com.qlinker.napcat.NapCatConnectionManager connections;
|
||||
private final boolean receiverEnabled;
|
||||
|
||||
public BootstrapRunner(BootstrapCoordinator coordinator, AuthService auth, CryptoService crypto,
|
||||
com.qlinker.napcat.NapCatConnectionManager connections, boolean receiverEnabled) {
|
||||
this.coordinator = coordinator;
|
||||
this.auth = auth;
|
||||
this.crypto = crypto;
|
||||
this.connections = connections;
|
||||
this.receiverEnabled = receiverEnabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run(ApplicationArguments args) {
|
||||
InstanceIdentity identity;
|
||||
try {
|
||||
identity = coordinator.ensureReady();
|
||||
} catch (RuntimeException e) {
|
||||
log.error("实例资源身份无法确认,管理接口将返回 503 直到人工修复:{}", e.getMessage());
|
||||
return;
|
||||
}
|
||||
log.info("实例就绪 instanceUid={} database={} bucket={} schema={}",
|
||||
identity.instanceUid(), identity.databaseName(), identity.bucketName(), identity.schemaVersion());
|
||||
|
||||
if (receiverEnabled) {
|
||||
// 事件接收必须在初始化成功后才启动:断线期间事件不补推,落库晚一秒就少一秒数据(能力基线)。
|
||||
connections.start();
|
||||
} else {
|
||||
log.warn("NapCat 事件接收已关闭(qlinker.napcat.receiver-enabled=false),不会接收任何消息");
|
||||
}
|
||||
|
||||
if (auth.hasAdministrator()) {
|
||||
return;
|
||||
}
|
||||
if (auth.hasBootstrapToken()) {
|
||||
log.warn("实例尚无管理员但已存在引导令牌记录,未重复签发。请使用首次启动时输出的令牌完成初始化");
|
||||
return;
|
||||
}
|
||||
String token = crypto.randomToken(24);
|
||||
Instant expiresAt = Instant.now().plus(BOOTSTRAP_TTL);
|
||||
try {
|
||||
auth.registerBootstrapToken(token, expiresAt);
|
||||
} catch (RuntimeException e) {
|
||||
log.error("引导令牌写入失败,无法完成首次初始化:{}", e.toString());
|
||||
return;
|
||||
}
|
||||
// 令牌明文只在此处输出一次,用于本机首次初始化;数据库只保存哈希(AGENTS.md 11.2)。
|
||||
log.warn("===== 首次初始化引导令牌(仅输出一次,有效期 24 小时)=====");
|
||||
log.warn("引导令牌: {}", token);
|
||||
log.warn("请在管理页面或 POST /api/v1/auth/bootstrap 使用该令牌创建唯一管理员账号");
|
||||
log.warn("==============================================================");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package com.qlinker.init;
|
||||
|
||||
import com.qlinker.config.QLinkerProperties;
|
||||
import io.minio.BucketExistsArgs;
|
||||
import io.minio.MakeBucketArgs;
|
||||
import io.minio.MinioClient;
|
||||
|
||||
/**
|
||||
* 独立 bucket 的创建与核验(AGENTS.md 12.1)。bucket 名由系统生成,不接受用户输入。
|
||||
*/
|
||||
public class BucketProvisioner {
|
||||
|
||||
private final QLinkerProperties properties;
|
||||
private final MinioClient client;
|
||||
|
||||
public BucketProvisioner(QLinkerProperties properties, MinioClient client) {
|
||||
this.properties = properties;
|
||||
this.client = client;
|
||||
}
|
||||
|
||||
public BucketProvisioner(QLinkerProperties properties) {
|
||||
this(properties, buildClient(properties));
|
||||
}
|
||||
|
||||
public static MinioClient buildClient(QLinkerProperties properties) {
|
||||
QLinkerProperties.Storage storage = properties.getStorage();
|
||||
if (storage.getEndpoint() == null || storage.getEndpoint().isBlank()
|
||||
|| storage.getAccessKey() == null || storage.getAccessKey().isBlank()
|
||||
|| storage.getSecretKey() == null || storage.getSecretKey().isBlank()) {
|
||||
throw new IllegalStateException("缺少对象存储配置:qlinker.storage.endpoint / access-key / secret-key");
|
||||
}
|
||||
return MinioClient.builder()
|
||||
.endpoint(storage.getEndpoint())
|
||||
.credentials(storage.getAccessKey(), storage.getSecretKey())
|
||||
.region(storage.getRegion())
|
||||
.build();
|
||||
}
|
||||
|
||||
public MinioClient client() {
|
||||
return client;
|
||||
}
|
||||
|
||||
public boolean bucketExists(String bucket) {
|
||||
try {
|
||||
return client.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("无法确认 bucket 是否存在:" + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/** 幂等创建 bucket;已存在时不改动其策略与内容。 */
|
||||
public void createBucket(String bucket) {
|
||||
if (!ResourceNames.isValidBucketName(bucket)) {
|
||||
throw new IllegalArgumentException("非法 bucket 名");
|
||||
}
|
||||
try {
|
||||
if (!client.bucketExists(BucketExistsArgs.builder().bucket(bucket).build())) {
|
||||
client.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("bucket 创建失败:" + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package com.qlinker.init;
|
||||
|
||||
import com.qlinker.config.QLinkerProperties;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
|
||||
/**
|
||||
* 隔离业务数据库的创建与存在性核验(AGENTS.md 12.1、12.3)。
|
||||
*
|
||||
* <p>只执行 {@code CREATE DATABASE IF NOT EXISTS} 与 {@code SELECT SCHEMA_NAME FROM information_schema},
|
||||
* 不对任何已存在的库执行 ALTER / DROP;库名由 {@link ResourceNames} 生成并做白名单校验后再拼接,
|
||||
* 不接受任何外部输入。</p>
|
||||
*/
|
||||
public class DatabaseProvisioner {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(DatabaseProvisioner.class);
|
||||
|
||||
private final QLinkerProperties properties;
|
||||
|
||||
public DatabaseProvisioner(QLinkerProperties properties) {
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
/** 连接到 MySQL 服务本身(不指定数据库),用于创建与核验业务库。 */
|
||||
Connection openServerConnection() throws Exception {
|
||||
QLinkerProperties.Instance cfg = properties.getInstance();
|
||||
String url = "jdbc:mysql://" + cfg.getMysqlHost() + ":" + cfg.getMysqlPort()
|
||||
+ "/?useSSL=false&allowPublicKeyRetrieval=true&connectionTimeZone=UTC&forceConnectionTimeZoneToSession=true";
|
||||
return DriverManager.getConnection(url, cfg.getMysqlUser(), cfg.getMysqlPassword());
|
||||
}
|
||||
|
||||
/** 业务库 JDBC 地址。 */
|
||||
public String businessJdbcUrl(String databaseName) {
|
||||
QLinkerProperties.Instance cfg = properties.getInstance();
|
||||
return "jdbc:mysql://" + cfg.getMysqlHost() + ":" + cfg.getMysqlPort() + "/" + databaseName
|
||||
+ "?useSSL=false&allowPublicKeyRetrieval=true&characterEncoding=utf8"
|
||||
+ "&connectionTimeZone=UTC&forceConnectionTimeZoneToSession=true"
|
||||
+ "&rewriteBatchedStatements=true&serverTimezone=UTC";
|
||||
}
|
||||
|
||||
public boolean databaseExists(String databaseName) {
|
||||
if (!ResourceNames.isValidDatabaseName(databaseName)) {
|
||||
throw new IllegalArgumentException("非法数据库名");
|
||||
}
|
||||
String sql = "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = ?";
|
||||
try (Connection c = openServerConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
|
||||
ps.setString(1, databaseName);
|
||||
try (ResultSet rs = ps.executeQuery()) {
|
||||
return rs.next();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("无法确认数据库是否存在:" + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建业务库。使用 IF NOT EXISTS 以满足初始化幂等(进程中断后重跑不报错)。
|
||||
* 排序规则显式指定 utf8mb4_0900_ai_ci,与迁移脚本保持一致,避免依赖服务端默认值。
|
||||
*/
|
||||
public void createDatabase(String databaseName) {
|
||||
if (!ResourceNames.isValidDatabaseName(databaseName)) {
|
||||
throw new IllegalArgumentException("非法数据库名");
|
||||
}
|
||||
String ddl = "CREATE DATABASE IF NOT EXISTS `" + databaseName + "` "
|
||||
+ "CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci";
|
||||
try (Connection c = openServerConnection(); PreparedStatement ps = c.prepareStatement(ddl)) {
|
||||
ps.execute();
|
||||
log.info("业务数据库已就绪 database={}", databaseName);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("业务数据库创建失败:" + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package com.qlinker.init;
|
||||
|
||||
/**
|
||||
* 实例身份与已创建资源的绑定关系。一旦持久化,后续启动只能复用,不得随机替换
|
||||
* (AGENTS.md 12.2、架构设计 13.3)。
|
||||
*
|
||||
* @param instanceUid QLinker 稳定身份
|
||||
* @param databaseName 实际业务数据库名
|
||||
* @param bucketName 实际对象存储 bucket 名
|
||||
* @param stage 初始化阶段,用于中断后判断已完成到哪一步
|
||||
* @param schemaVersion 已应用的数据库结构版本
|
||||
*/
|
||||
public record InstanceIdentity(String instanceUid,
|
||||
String databaseName,
|
||||
String bucketName,
|
||||
Stage stage,
|
||||
String schemaVersion) {
|
||||
|
||||
/**
|
||||
* 初始化阶段(架构设计 13.3)。顺序即恢复顺序,只允许向前推进。
|
||||
*/
|
||||
public enum Stage {
|
||||
/** 已确定资源名称但尚未创建任何资源。 */
|
||||
PLANNED,
|
||||
/** 业务数据库已创建。 */
|
||||
DATABASE_CREATED,
|
||||
/** bucket 已创建。 */
|
||||
BUCKET_CREATED,
|
||||
/** 数据库结构迁移已完成。 */
|
||||
SCHEMA_MIGRATED,
|
||||
/** 初始化完成,可对外提供服务。 */
|
||||
READY,
|
||||
/** 身份与真实资源不一致或资源缺失,需要人工介入;此状态下禁止自动新建资源。 */
|
||||
RECOVERY_REQUIRED;
|
||||
|
||||
public boolean isBlocked() {
|
||||
return this == RECOVERY_REQUIRED;
|
||||
}
|
||||
|
||||
boolean atLeast(Stage other) {
|
||||
return this.ordinal() >= other.ordinal();
|
||||
}
|
||||
}
|
||||
|
||||
public InstanceIdentity withStage(Stage newStage) {
|
||||
return new InstanceIdentity(instanceUid, databaseName, bucketName, newStage, schemaVersion);
|
||||
}
|
||||
|
||||
public InstanceIdentity withSchemaVersion(String version) {
|
||||
return new InstanceIdentity(instanceUid, databaseName, bucketName, stage, version);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package com.qlinker.init;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.node.ObjectNode;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* 实例身份状态文件:资源身份的持久化载体,也是重启后复用资源的唯一依据。
|
||||
*
|
||||
* <p>选择本地文件而非业务库,是因为业务库本身要等身份确定后才能连接;
|
||||
* 状态文件与业务库/bucket 中的 {@code system_instance} 记录构成双向校验,
|
||||
* 任一侧缺失或不一致时进入 RECOVERY_REQUIRED,禁止自动新建资源(AGENTS.md 12.2)。</p>
|
||||
*/
|
||||
public class InstanceStateStore {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(InstanceStateStore.class);
|
||||
public static final String FILE_NAME = "instance-state.json";
|
||||
|
||||
private final Path file;
|
||||
private final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
public InstanceStateStore(String stateDir) {
|
||||
this.file = Path.of(stateDir).resolve(FILE_NAME);
|
||||
}
|
||||
|
||||
public Path stateFile() {
|
||||
return file;
|
||||
}
|
||||
|
||||
public Optional<InstanceState> read() {
|
||||
if (!Files.exists(file)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
ObjectNode node = (ObjectNode) mapper.readTree(Files.readString(file, StandardCharsets.UTF_8));
|
||||
return Optional.of(new InstanceState(
|
||||
text(node, "instanceUid"),
|
||||
text(node, "databaseName"),
|
||||
text(node, "bucketName"),
|
||||
InstanceIdentity.Stage.valueOf(node.path("stage").asText(InstanceIdentity.Stage.PLANNED.name())),
|
||||
node.path("schemaVersion").asText(null)));
|
||||
} catch (Exception e) {
|
||||
// 状态文件损坏不能被视为「未初始化」,否则会绕过保护重新创建一套空资源。
|
||||
log.error("实例状态文件无法解析 path={} error={}", file, e.toString());
|
||||
return Optional.of(new InstanceState(null, null, null, InstanceIdentity.Stage.RECOVERY_REQUIRED, null));
|
||||
}
|
||||
}
|
||||
|
||||
public void write(InstanceState state) {
|
||||
try {
|
||||
Files.createDirectories(file.getParent());
|
||||
ObjectNode node = mapper.createObjectNode();
|
||||
node.put("instanceUid", state.instanceUid());
|
||||
node.put("databaseName", state.databaseName());
|
||||
node.put("bucketName", state.bucketName());
|
||||
node.put("stage", state.stage().name());
|
||||
node.put("schemaVersion", state.schemaVersion());
|
||||
Path tmp = file.resolveSibling(FILE_NAME + ".tmp");
|
||||
Files.writeString(tmp, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node),
|
||||
StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
|
||||
try {
|
||||
Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
|
||||
} catch (IOException e) {
|
||||
Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new IllegalStateException("实例状态文件写入失败 path=" + file, e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String text(ObjectNode node, String field) {
|
||||
String value = node.path(field).asText(null);
|
||||
return value == null || value.isBlank() ? null : value;
|
||||
}
|
||||
|
||||
public record InstanceState(String instanceUid,
|
||||
String databaseName,
|
||||
String bucketName,
|
||||
InstanceIdentity.Stage stage,
|
||||
String schemaVersion) {
|
||||
|
||||
public InstanceIdentity toIdentity() {
|
||||
return new InstanceIdentity(instanceUid, databaseName, bucketName, stage, schemaVersion);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
package com.qlinker.init;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* 隔离资源命名(AGENTS.md 12.1)。
|
||||
*
|
||||
* <p>随机标识使用 {@link SecureRandom},字符集为小写字母与数字:对象存储 bucket 名
|
||||
* 只允许小写字母、数字与连字符;MySQL 的 {@code lower_case_table_names=1} 会把库名
|
||||
* 折叠为小写,而 Linux 上更常见的 {@code lower_case_table_names=0} 区分大小写。</p>
|
||||
*
|
||||
* <p>本项目始终只生成、持久化并使用同一个小写库名,因此两种设置下身份名与实际资源名
|
||||
* 都保持一致;与 AGENTS.md 12.1 写作 {@code Qlinker_} 的差异仅是命名书写大小写,
|
||||
* 不改变隔离边界,也不影响 Flyway 迁移。不得为对齐书写而重命名已初始化实例的库或 bucket。</p>
|
||||
*/
|
||||
public final class ResourceNames {
|
||||
|
||||
/** 数据库名前缀。与 AGENTS.md 12.1 的书写大小写差异及 Linux 影响见任务 004 交付文档。 */
|
||||
public static final String DATABASE_PREFIX = "qlinker_";
|
||||
public static final String BUCKET_PREFIX = "qlinker-";
|
||||
|
||||
private static final char[] ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
|
||||
private static final Pattern DATABASE_NAME = Pattern.compile("^qlinker_[a-z0-9]{8}$");
|
||||
private static final Pattern BUCKET_NAME = Pattern.compile("^qlinker-[a-z0-9]{8}$");
|
||||
|
||||
private ResourceNames() {
|
||||
}
|
||||
|
||||
public static String randomId(SecureRandom random, int length) {
|
||||
if (length < 6 || length > 32) {
|
||||
throw new IllegalArgumentException("随机标识长度必须在 6 到 32 之间");
|
||||
}
|
||||
StringBuilder sb = new StringBuilder(length);
|
||||
for (int i = 0; i < length; i++) {
|
||||
sb.append(ALPHABET[random.nextInt(ALPHABET.length)]);
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static String databaseName(String randomId) {
|
||||
String name = (DATABASE_PREFIX + randomId).toLowerCase(Locale.ROOT);
|
||||
if (!DATABASE_NAME.matcher(name).matches()) {
|
||||
throw new IllegalArgumentException("数据库名不满足命名规则: " + name);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
public static String bucketName(String randomId) {
|
||||
String name = (BUCKET_PREFIX + randomId).toLowerCase(Locale.ROOT);
|
||||
if (!BUCKET_NAME.matcher(name).matches() || name.length() > 63) {
|
||||
throw new IllegalArgumentException("bucket 名不满足命名规则: " + name);
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
public static boolean isValidDatabaseName(String name) {
|
||||
return name != null && DATABASE_NAME.matcher(name).matches();
|
||||
}
|
||||
|
||||
public static boolean isValidBucketName(String name) {
|
||||
return name != null && BUCKET_NAME.matcher(name).matches();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.qlinker.init;
|
||||
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.flywaydb.core.api.MigrationInfo;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
/**
|
||||
* 显式执行 Flyway 迁移。迁移只在初始化编排内触发,不依赖 Spring Boot 的自动迁移,
|
||||
* 保证「先确定资源身份、再建表」的顺序可控(数据库设计 20.1、20.2)。
|
||||
*/
|
||||
public class SchemaMigrator {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SchemaMigrator.class);
|
||||
|
||||
public String migrate(DataSource dataSource) {
|
||||
Flyway flyway = Flyway.configure()
|
||||
.dataSource(dataSource)
|
||||
.locations("classpath:db/migration")
|
||||
.baselineOnMigrate(false)
|
||||
.cleanDisabled(true)
|
||||
.table("flyway_schema_history")
|
||||
.load();
|
||||
var result = flyway.migrate();
|
||||
String version = currentVersion(dataSource);
|
||||
log.info("数据库迁移完成 applied={} version={}", result.migrationsExecuted, version);
|
||||
return version;
|
||||
}
|
||||
|
||||
public String currentVersion(DataSource dataSource) {
|
||||
Flyway flyway = Flyway.configure()
|
||||
.dataSource(dataSource)
|
||||
.locations("classpath:db/migration")
|
||||
.table("flyway_schema_history")
|
||||
.load();
|
||||
MigrationInfo current = flyway.info().current();
|
||||
return current == null || current.getVersion() == null ? null : current.getVersion().getVersion();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user