已将业务时间生成入口统一为 Asia/Shanghai,不依赖服务器默认时区
This commit is contained in:
+2
-1
@@ -1,5 +1,6 @@
|
||||
# 复制为 .env;此文件不能填写真实凭据后提交。
|
||||
DB_URL='jdbc:mysql://localhost:3306/vibemake?useUnicode=true&characterEncoding=utf8&connectionTimeZone=UTC'
|
||||
# 业务时间统一使用 Asia/Shanghai。
|
||||
DB_URL='jdbc:mysql://localhost:3306/vibemake?useUnicode=true&characterEncoding=utf8&connectionTimeZone=Asia/Shanghai'
|
||||
DB_USERNAME=vibemake_app
|
||||
DB_PASSWORD='replace-with-your-database-password'
|
||||
GITEA_BASE_URL=http://localhost:3000
|
||||
|
||||
@@ -20,7 +20,7 @@ Spring Boot 社区后端,工程分层参考 cadworld。使用 Java 21、Spring
|
||||
| vibemake-adminapi | 独立管理端应用,用户角色鉴权、用户与全站项目管理、GitHub 在线迁移 |
|
||||
| vibemake-import | 固定 Excel 的 GitHub 项目运维导入命令,不提供 HTTP 接口 |
|
||||
|
||||
UserService、ProjectService、FileService、InteractionService、CoverUploadService、UrdfService 采用接口加实现类,Controller、安全模块和服务之间通过接口注入。GiteaClient 与 RestGiteaClient 定义仓库调用边界;项目锁、UTC 时间和分页检查归入 support。安全模块内的 TokenService、CaptchaService 保留具体类,短期状态使用 Redis,限流和共享响应组装位于 service。
|
||||
UserService、ProjectService、FileService、InteractionService、CoverUploadService、UrdfService 采用接口加实现类,Controller、安全模块和服务之间通过接口注入。GiteaClient 与 RestGiteaClient 定义仓库调用边界;项目锁、上海业务时间(Asia/Shanghai)和分页检查归入 support。安全模块内的 TokenService、CaptchaService 保留具体类,短期状态使用 Redis,限流和共享响应组装位于 service。
|
||||
|
||||
## 功能与边界
|
||||
|
||||
@@ -77,6 +77,8 @@ SPRING_PROFILES_ACTIVE=prod java -Djava.awt.headless=true -jar vibemake-api/targ
|
||||
|
||||
同时输出控制台、vibemake-api.log 和 vibemake-api-error.log,日志时间使用 Asia/Shanghai,格式包含线程、级别、requestId 和类名。应用日志按天或每 100MB 归档,保留 30 天、总归档上限 10GB;错误日志仅接收 ERROR,按天或每 50MB 归档,保留 60 天、总归档上限 5GB。归档写入 archive 子目录并压缩为 gzip。SQL Mapper 和 Spring Web 保持 INFO,不记录凭据、邮箱或代码内容。
|
||||
|
||||
业务数据库与接口中的日期时间统一使用 `Asia/Shanghai`,不依赖服务器默认时区;接口中不带时区后缀的时间需按 `+08:00` 解析。OSS 签名协议字段保留 UTC,Git 提交日期保留原时区。已有 UTC 数据库升级前,先按[业务时间迁移说明](docs/admin-database.md#业务时间由-utc-迁移到上海时间)完成一次性转换,再同时部署社区端、管理端与导入工具;前端同步调整解析方式。
|
||||
|
||||
## 验证
|
||||
|
||||
```bash
|
||||
@@ -248,6 +250,8 @@ bash scripts/import-github-projects.sh --excel "$IMPORT_EXCEL" --execute --owner
|
||||
|
||||
`--owner-email` 可替代 `--owner-user-code` 查找已有账号,二者互斥,工具不会创建用户;状态中始终保存查到的用户编码。`--state-dir` 默认 `logs/github-import`,包含原子写入的 `manifest.json` 和 `report.json`;此目录必须保留并备份,不能在迁移进行中删除。清单绑定 Excel 指纹、归属用户和 Gitea 目标,不能复用于另一文件或环境。同一目录有进程锁,`--concurrency` 默认为 2,可选 1~4;同一批次只运行一个进程。`--limit` 限制尚未完成候选的处理数量;已完成项目、迁移结果未知或不具备收据核对条件的 REVIEW 项目不计入。
|
||||
|
||||
导入清单和报告通过 `timeZone` 声明 `Asia/Shanghai`。旧版未声明时区的清单首次由新版读取时,会将 `reservedAt` 从 UTC 转为上海时间并原子保存,之后续跑不会重复转换;应先完成业务库历史时间迁移,并备份状态目录后再使用新版续跑。
|
||||
|
||||
工具先创建 CREATING 项目记录,直接调用 Gitea `/repos/migrate`,不先创建空仓库。迁移使用私有普通仓库、开启 LFS,保留 Git 内容、历史、分支和标签;不迁移工单、PR、Wiki 或 Release 附件。迁移成功收据先落盘,再关联项目并自动发布。独立迁移请求默认超时 1800 秒,可用 `--migration-timeout-seconds` 调整,普通 Gitea 请求超时不变。原默认分支不是 main 时补建 main 并设为默认,保留原分支;同名 main 内容冲突时停止该项目,不覆盖源分支或已冻结版本。
|
||||
|
||||
进程在 MIGRATING 阶段中断,或迁移超时、结果不明确时,项目进入 REVIEW,禁止自动重发或仅凭仓库存在判定成功。需要核对 Gitea 迁移及 LFS 完成情况、来源和提交后由维护人员处理;不要直接把 REVIEW 改为 READY 或删除仓库再重跑。已确认的迁移收据会用于数据库回写或发布失败后的续跑,避免重复迁移。对于已持久化成功收据、仅在主分支适配时出现不明写入结果的项目,续跑先只读核对仓库身份、来源、私有属性、默认分支和两条分支的冻结 SHA;全部一致才继续关联和发布,否则保持 REVIEW,不重发分支写入。已完成项目不会因后续人工撤回、修改或删除而被批次重新发布。
|
||||
|
||||
+13
-13
@@ -87,7 +87,7 @@
|
||||
### 2.2 时间和公共类型
|
||||
|
||||
```ts
|
||||
type UtcDateTime = string;
|
||||
type ShanghaiDateTime = string;
|
||||
|
||||
interface ApiResponse<T> {
|
||||
code: string;
|
||||
@@ -104,11 +104,11 @@ interface PageResponse<T> {
|
||||
}
|
||||
```
|
||||
|
||||
`createdAt`、`updatedAt`、`publishedAt`、`expiresAt`、`startedAt`、`finishedAt` 为 UTC 时间字符串,例如 `2026-10-20T02:30:00.123`,当前没有时区后缀。前端按 UTC 解析后再格式化为本地时间,不能直接当作北京时间。提交历史的 `authorDate` 沿用 Git 日期,可能自带 `Z` 或时区偏移。
|
||||
`createdAt`、`updatedAt`、`publishedAt`、`expiresAt`、`startedAt`、`finishedAt` 为上海时间(`Asia/Shanghai`,UTC+8)字符串,例如 `2026-10-20T10:30:00.123`,当前没有时区后缀。前端应补充 `+08:00` 后解析,再格式化为用户本地时间;不能继续补 `Z`,也不能依赖浏览器默认时区。前后端需同时切换时间约定,避免多显示 8 小时。提交历史的 `authorDate` 沿用 Git 日期,可能自带 `Z` 或时区偏移。
|
||||
|
||||
```ts
|
||||
function parseServerTime(value: string): Date {
|
||||
return new Date(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}Z`);
|
||||
return new Date(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}+08:00`);
|
||||
}
|
||||
```
|
||||
|
||||
@@ -281,7 +281,7 @@ interface UserView {
|
||||
status: UserStatus;
|
||||
role: UserRole;
|
||||
projectCount: number; // 名下未删除项目数
|
||||
createdAt: UtcDateTime;
|
||||
createdAt: ShanghaiDateTime;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -349,7 +349,7 @@ interface ProjectView {
|
||||
repoStatus: RepoStatus;
|
||||
publishStatus: PublishStatus;
|
||||
publishedCommitSha: string | null;
|
||||
publishedAt: UtcDateTime | null;
|
||||
publishedAt: ShanghaiDateTime | null;
|
||||
sourceProjectCode: string | null;
|
||||
sourceCommitSha: string | null;
|
||||
likeCount: number;
|
||||
@@ -357,8 +357,8 @@ interface ProjectView {
|
||||
liked: boolean;
|
||||
sourceRepositoryUrl: string | null;
|
||||
sourceLicense: string | null;
|
||||
createdAt: UtcDateTime;
|
||||
updatedAt: UtcDateTime;
|
||||
createdAt: ShanghaiDateTime;
|
||||
updatedAt: ShanghaiDateTime;
|
||||
}
|
||||
|
||||
interface ManagedProjectView {
|
||||
@@ -711,7 +711,7 @@ interface CoverUploadSignature {
|
||||
uploadUrl: string;
|
||||
objectKey: string;
|
||||
coverUrl: string;
|
||||
expiresAt: UtcDateTime;
|
||||
expiresAt: ShanghaiDateTime;
|
||||
formFields: Record<string, string>;
|
||||
}
|
||||
```
|
||||
@@ -771,7 +771,7 @@ interface UrdfUploadSignature {
|
||||
batchCode: string;
|
||||
mainRelativePath: string;
|
||||
uploadUrl: string;
|
||||
expiresAt: UtcDateTime;
|
||||
expiresAt: ShanghaiDateTime;
|
||||
files: UrdfFileSignature[];
|
||||
}
|
||||
```
|
||||
@@ -849,7 +849,7 @@ interface ResourceFile { relativePath: string; sizeBytes: number }
|
||||
interface ResourceUploadSignature {
|
||||
batchCode: string;
|
||||
uploadUrl: string;
|
||||
expiresAt: UtcDateTime;
|
||||
expiresAt: ShanghaiDateTime;
|
||||
files: { relativePath: string; objectKey: string; formFields: Record<string, string> }[];
|
||||
}
|
||||
|
||||
@@ -1026,9 +1026,9 @@ interface TaskView {
|
||||
canRetry: boolean;
|
||||
retryMessage: string | null;
|
||||
warnings: string[];
|
||||
createdAt: UtcDateTime;
|
||||
startedAt: UtcDateTime | null;
|
||||
finishedAt: UtcDateTime | null;
|
||||
createdAt: ShanghaiDateTime;
|
||||
startedAt: ShanghaiDateTime | null;
|
||||
finishedAt: ShanghaiDateTime | null;
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
+84
-9
@@ -2,7 +2,7 @@
|
||||
|
||||
以下 SQL 由维护人员手工执行,应用不会自动迁库。已有数据库执行下面的增量 SQL;新建数据库先执行 database.md 中的四表 SQL,然后只创建本文件的任务表,不重复执行 ALTER。
|
||||
|
||||
执行前暂停社区端、后台和导入工具的写入并备份数据库。不要对已有列重复执行。所有时间字段由应用写入 UTC。项目来源改为从任务表读取,因此社区端、后台和导入工具升级前都应创建任务表,即使暂不启动后台也需要执行。
|
||||
执行前暂停社区端、后台和导入工具的写入并备份数据库。不要对已有列重复执行。所有时间字段由应用写入上海时间(Asia/Shanghai,UTC+8)。项目来源改为从任务表读取,因此社区端、后台和导入工具升级前都应创建任务表,即使暂不启动后台也需要执行。
|
||||
|
||||
## 项目字段收敛
|
||||
|
||||
@@ -69,10 +69,10 @@ CREATE TABLE project_import_task (
|
||||
target_sha VARCHAR(64) NULL COMMENT '迁移后冻结的目标提交SHA',
|
||||
error_code VARCHAR(64) NULL COMMENT '最近失败错误码',
|
||||
warnings_json TEXT NOT NULL COMMENT '兼容性提醒JSON数组',
|
||||
started_at DATETIME(3) NULL COMMENT '最近开始时间UTC',
|
||||
finished_at DATETIME(3) NULL COMMENT '最近结束时间UTC',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间UTC',
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '更新时间UTC',
|
||||
started_at DATETIME(3) NULL COMMENT '最近开始时间(Asia/Shanghai)',
|
||||
finished_at DATETIME(3) NULL COMMENT '最近结束时间(Asia/Shanghai)',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间(Asia/Shanghai)',
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '更新时间(Asia/Shanghai)',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_import_task_code (task_code),
|
||||
UNIQUE KEY uk_import_project (project_code),
|
||||
@@ -120,7 +120,7 @@ ALTER TABLE project MODIFY COLUMN publish_status VARCHAR(16) NOT NULL DEFAULT 'U
|
||||
|
||||
## 新建普通文件写入操作记录表(本次上线前执行)
|
||||
|
||||
只新增此表,不需要修改项目表。由运维手工执行;应用不自动迁库。时间全部为 UTC。
|
||||
只新增此表,不需要修改项目表。由运维手工执行;应用不自动迁库。时间全部为上海时间(Asia/Shanghai,UTC+8)。
|
||||
|
||||
```sql
|
||||
CREATE TABLE repository_write_operation (
|
||||
@@ -137,9 +137,9 @@ CREATE TABLE repository_write_operation (
|
||||
failure_status INT NULL COMMENT '明确失败时原HTTP状态码',
|
||||
last_error_code VARCHAR(64) NULL COMMENT '最近核对错误编码,不保存异常正文或凭证',
|
||||
check_count INT NOT NULL DEFAULT 0 COMMENT '后台已执行核对次数',
|
||||
next_check_at DATETIME(3) NOT NULL COMMENT '下次只读核对时间UTC',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间UTC',
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '最近更新时间UTC',
|
||||
next_check_at DATETIME(3) NOT NULL COMMENT '下次只读核对时间(Asia/Shanghai)',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间(Asia/Shanghai)',
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '最近更新时间(Asia/Shanghai)',
|
||||
PRIMARY KEY (operation_code),
|
||||
KEY idx_write_project_status (project_code, status, created_at),
|
||||
KEY idx_write_next_check (status, next_check_at)
|
||||
@@ -147,3 +147,78 @@ CREATE TABLE repository_write_operation (
|
||||
```
|
||||
|
||||
已完成的操作记录仍用于幂等重放,不要在客户端可能重试期间删除。历史 REVIEW 没有操作记录,不会凭最新 SHA 自动判成功;需核对实际结果后按原维护流程处理。迁移、Fork 继续使用原流程。
|
||||
|
||||
## 业务时间由 UTC 迁移到上海时间
|
||||
|
||||
新版统一通过 `ProjectSupport` 生成上海时间(`Asia/Shanghai`),字段类型保持 `DATETIME(3)`。以下 SQL 由维护人员手工执行,应用不会执行迁移,也不会自动修改已有数据库。
|
||||
|
||||
执行顺序:暂停社区端、管理端和导入工具,备份业务数据库及导入状态目录;确认以下六张表中的历史时间仍全部为 UTC 后执行一次转换;核对结果后同时部署新版各模块,并同步前端的 `+08:00` 解析方式,再恢复服务。新建空库无需执行数据转换。若已经写入上海时间或存在混合时区数据,必须先按切换记录确定待转换数据范围,不能直接执行以下全表更新;本脚本不能重复执行。
|
||||
|
||||
```sql
|
||||
USE vibemake;
|
||||
START TRANSACTION;
|
||||
|
||||
UPDATE sys_user
|
||||
SET created_at = DATE_ADD(created_at, INTERVAL 8 HOUR),
|
||||
updated_at = DATE_ADD(updated_at, INTERVAL 8 HOUR);
|
||||
|
||||
UPDATE project
|
||||
SET created_at = DATE_ADD(created_at, INTERVAL 8 HOUR),
|
||||
updated_at = DATE_ADD(updated_at, INTERVAL 8 HOUR),
|
||||
published_at = DATE_ADD(published_at, INTERVAL 8 HOUR);
|
||||
|
||||
UPDATE project_comment
|
||||
SET created_at = DATE_ADD(created_at, INTERVAL 8 HOUR),
|
||||
updated_at = DATE_ADD(updated_at, INTERVAL 8 HOUR);
|
||||
|
||||
UPDATE project_like
|
||||
SET created_at = DATE_ADD(created_at, INTERVAL 8 HOUR);
|
||||
|
||||
UPDATE project_import_task
|
||||
SET created_at = DATE_ADD(created_at, INTERVAL 8 HOUR),
|
||||
updated_at = DATE_ADD(updated_at, INTERVAL 8 HOUR),
|
||||
started_at = DATE_ADD(started_at, INTERVAL 8 HOUR),
|
||||
finished_at = DATE_ADD(finished_at, INTERVAL 8 HOUR);
|
||||
|
||||
UPDATE repository_write_operation
|
||||
SET created_at = DATE_ADD(created_at, INTERVAL 8 HOUR),
|
||||
updated_at = DATE_ADD(updated_at, INTERVAL 8 HOUR),
|
||||
next_check_at = DATE_ADD(next_check_at, INTERVAL 8 HOUR);
|
||||
|
||||
COMMIT;
|
||||
```
|
||||
|
||||
空值保持为空,毫秒精度保持不变。`next_check_at` 等调度时间也需要转换,避免切换后提前或延后核对任务。Git 提交日期、OSS 签名内容和 Gitea 内部数据库不参与转换。
|
||||
|
||||
已有数据库的时间字段注释可单独按以下 SQL 更新;DDL 会隐式提交,不要放入上面的数据转换事务。
|
||||
|
||||
```sql
|
||||
ALTER TABLE sys_user
|
||||
MODIFY COLUMN created_at DATETIME(3) NOT NULL COMMENT '创建时间(Asia/Shanghai)',
|
||||
MODIFY COLUMN updated_at DATETIME(3) NOT NULL COMMENT '更新时间(Asia/Shanghai)';
|
||||
|
||||
ALTER TABLE project
|
||||
MODIFY COLUMN created_at DATETIME(3) NOT NULL COMMENT '创建时间(Asia/Shanghai)',
|
||||
MODIFY COLUMN updated_at DATETIME(3) NOT NULL COMMENT '更新时间(Asia/Shanghai)',
|
||||
MODIFY COLUMN published_at DATETIME(3) NULL COMMENT '最近发布时间(Asia/Shanghai)';
|
||||
|
||||
ALTER TABLE project_comment
|
||||
MODIFY COLUMN created_at DATETIME(3) NOT NULL COMMENT '创建时间(Asia/Shanghai)',
|
||||
MODIFY COLUMN updated_at DATETIME(3) NOT NULL COMMENT '更新时间(Asia/Shanghai)';
|
||||
|
||||
ALTER TABLE project_like
|
||||
MODIFY COLUMN created_at DATETIME(3) NOT NULL COMMENT '点赞时间(Asia/Shanghai)';
|
||||
|
||||
ALTER TABLE project_import_task
|
||||
MODIFY COLUMN created_at DATETIME(3) NOT NULL COMMENT '创建时间(Asia/Shanghai)',
|
||||
MODIFY COLUMN updated_at DATETIME(3) NOT NULL COMMENT '更新时间(Asia/Shanghai)',
|
||||
MODIFY COLUMN started_at DATETIME(3) NULL COMMENT '最近开始时间(Asia/Shanghai)',
|
||||
MODIFY COLUMN finished_at DATETIME(3) NULL COMMENT '最近结束时间(Asia/Shanghai)';
|
||||
|
||||
ALTER TABLE repository_write_operation
|
||||
MODIFY COLUMN created_at DATETIME(3) NOT NULL COMMENT '创建时间(Asia/Shanghai)',
|
||||
MODIFY COLUMN updated_at DATETIME(3) NOT NULL COMMENT '最近更新时间(Asia/Shanghai)',
|
||||
MODIFY COLUMN next_check_at DATETIME(3) NOT NULL COMMENT '下次只读核对时间(Asia/Shanghai)';
|
||||
```
|
||||
|
||||
旧导入状态首次由新版读取时,将未声明时区的 `reservedAt` 从 UTC 转为上海时间,原子保存并标记 `timeZone=Asia/Shanghai`,后续不会再次转换。应在业务库完成转换后再续跑;未迁移的数据库时间与清单不一致时,现有归属校验会阻止接管项目。回滚应用前需要同时恢复数据库和导入状态备份,并恢复前端的旧时间解析约定。
|
||||
|
||||
+9
-9
@@ -15,8 +15,8 @@ CREATE TABLE sys_user (
|
||||
role VARCHAR(16) NOT NULL DEFAULT 'USER' COMMENT '用户角色 USER普通用户 ADMIN管理员 OFFICIAL官方托管账号',
|
||||
password_hash VARCHAR(100) NULL COMMENT '管理员BCrypt密码哈希,普通用户为空',
|
||||
session_version BIGINT NOT NULL DEFAULT 0 COMMENT '登录会话版本,禁用或修改密码时递增',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间 UTC',
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '更新时间 UTC',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间(Asia/Shanghai)',
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '更新时间(Asia/Shanghai)',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_user_code (user_code),
|
||||
UNIQUE KEY uk_user_email (email)
|
||||
@@ -47,14 +47,14 @@ CREATE TABLE project (
|
||||
repo_status VARCHAR(16) NOT NULL DEFAULT 'CREATING' COMMENT '仓库状态 CREATING READY FAILED',
|
||||
publish_status VARCHAR(16) NOT NULL DEFAULT 'UNPUBLISHED' COMMENT '发布状态 UNPUBLISHED未发布 PUBLISHED已发布 BLOCKED管理员下架',
|
||||
published_commit_sha VARCHAR(64) NULL COMMENT '社区已发布 Commit SHA',
|
||||
published_at DATETIME(3) NULL COMMENT '最近发布时间 UTC',
|
||||
published_at DATETIME(3) NULL COMMENT '最近发布时间(Asia/Shanghai)',
|
||||
moderation_reason VARCHAR(500) NULL COMMENT '管理员下架原因',
|
||||
repo_write_status VARCHAR(16) NOT NULL DEFAULT 'IDLE' COMMENT '仓库写入状态 IDLE空闲 WRITING写入中 REVIEW待核对',
|
||||
source_project_id BIGINT NULL COMMENT 'Fork 来源项目',
|
||||
source_commit_sha VARCHAR(64) NULL COMMENT 'Fork 来源已发布 Commit SHA',
|
||||
deleted TINYINT(1) NOT NULL DEFAULT 0 COMMENT '逻辑删除标识',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间 UTC',
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '更新时间 UTC',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间(Asia/Shanghai)',
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '更新时间(Asia/Shanghai)',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_project_code (project_code),
|
||||
UNIQUE KEY uk_project_repo (gitea_owner, gitea_repo_name),
|
||||
@@ -73,8 +73,8 @@ CREATE TABLE project_comment (
|
||||
user_id BIGINT NOT NULL COMMENT '评论用户',
|
||||
content TEXT NOT NULL COMMENT '纯文本评论内容',
|
||||
deleted TINYINT(1) NOT NULL DEFAULT 0 COMMENT '逻辑删除标识',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间 UTC',
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '更新时间 UTC',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '创建时间(Asia/Shanghai)',
|
||||
updated_at DATETIME(3) NOT NULL COMMENT '更新时间(Asia/Shanghai)',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_comment_code (comment_code),
|
||||
KEY idx_comment_project (project_id, deleted, created_at),
|
||||
@@ -86,7 +86,7 @@ CREATE TABLE project_like (
|
||||
id BIGINT NOT NULL AUTO_INCREMENT COMMENT '内部点赞主键',
|
||||
project_id BIGINT NOT NULL COMMENT '所属项目',
|
||||
user_id BIGINT NOT NULL COMMENT '点赞用户',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '点赞时间 UTC',
|
||||
created_at DATETIME(3) NOT NULL COMMENT '点赞时间(Asia/Shanghai)',
|
||||
PRIMARY KEY (id),
|
||||
UNIQUE KEY uk_like_project_user (project_id, user_id),
|
||||
CONSTRAINT fk_like_project FOREIGN KEY (project_id) REFERENCES project(id),
|
||||
@@ -94,7 +94,7 @@ CREATE TABLE project_like (
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='项目点赞';
|
||||
```
|
||||
|
||||
内部 ID 仅用于数据库关联,对外使用业务编码。时间均由后端写入 UTC。`CREATING` 项目表示仓库初始化未完成,不代表编辑草稿。Gitea 数据库与业务库分离,不修改 Gitea 内部表。
|
||||
内部 ID 仅用于数据库关联,对外使用业务编码。时间均由后端写入上海时间(Asia/Shanghai,UTC+8)。`CREATING` 项目表示仓库初始化未完成,不代表编辑草稿。Gitea 数据库与业务库分离,不修改 Gitea 内部表。
|
||||
|
||||
新增项目和用户使用 12 位小写字母和数字编码,历史 32 位编码继续保留。现有 `project_code CHAR(32)` 和 `user_code CHAR(32)` 可容纳两者,不需要修改表结构或历史记录;仓库名称仍为 `p_{projectCode}`。用户编码由安全随机数生成,唯一索引兜底,冲突时最多尝试 5 次;同一邮箱并发注册复用已有用户。评论编码保持 32 位。GitHub 运维导入的来源和进度保存于批次状态目录,GitHub 来源不占用社区内部 Fork 来源字段。
|
||||
|
||||
|
||||
+14
-14
@@ -90,7 +90,7 @@
|
||||
|
||||
### 时间和版本
|
||||
|
||||
项目和评论的时间字段按 UTC 保存,JSON 格式为 `2026-10-13T08:30:00`,可能带小数秒,**没有时区后缀**。前端解析这些字段时应按 UTC 处理,再转换成用户时区;不要直接当成本地时间。历史提交的 `authorDate` 来自仓库服务,可带 `Z` 或时区偏移。
|
||||
项目、评论及上传过期时间统一使用上海时间(`Asia/Shanghai`,UTC+8),JSON 格式为 `2026-10-13T08:30:00`,可能带小数秒,**没有时区后缀**。前端解析这些字段时应补充 `+08:00`,再转换成用户时区;不能继续补 `Z` 或依赖浏览器本地时区。历史提交的 `authorDate` 来自仓库服务,可带 `Z` 或时区偏移。
|
||||
|
||||
Git SHA 使用完整的 40 或 64 位十六进制字符串,不使用缩写。几个版本字段的用途不同:
|
||||
|
||||
@@ -149,8 +149,8 @@ Git SHA 使用完整的 40 或 64 位十六进制字符串,不使用缩写。
|
||||
以下 TypeScript 类型与当前 JSON 字段对应。项目列表、工作区详情、社区详情、创建、修改、发布和 Fork 共用 Project 结构。
|
||||
|
||||
```typescript
|
||||
/** 无时区后缀,按 UTC 解释。 */
|
||||
export type UtcDateTime = string;
|
||||
/** 无时区后缀,按 Asia/Shanghai(UTC+8)解释。 */
|
||||
export type ShanghaiDateTime = string;
|
||||
|
||||
export interface ApiResponse<T> {
|
||||
code: string;
|
||||
@@ -219,7 +219,7 @@ export interface Project {
|
||||
repoStatus: 'CREATING' | 'READY' | 'FAILED';
|
||||
publishStatus: 'UNPUBLISHED' | 'PUBLISHED' | 'BLOCKED';
|
||||
publishedCommitSha: string | null;
|
||||
publishedAt: UtcDateTime | null;
|
||||
publishedAt: ShanghaiDateTime | null;
|
||||
sourceProjectCode: string | null;
|
||||
sourceCommitSha: string | null;
|
||||
sourceRepositoryUrl: string | null; // 在线迁移任务记录的原仓库地址
|
||||
@@ -227,15 +227,15 @@ export interface Project {
|
||||
likeCount: number;
|
||||
commentCount: number;
|
||||
liked: boolean;
|
||||
createdAt: UtcDateTime;
|
||||
updatedAt: UtcDateTime;
|
||||
createdAt: ShanghaiDateTime;
|
||||
updatedAt: ShanghaiDateTime;
|
||||
}
|
||||
|
||||
export interface CoverUploadSignature {
|
||||
uploadUrl: string;
|
||||
objectKey: string;
|
||||
coverUrl: string;
|
||||
expiresAt: UtcDateTime; // 无时区后缀,按 UTC 解释
|
||||
expiresAt: ShanghaiDateTime; // 无时区后缀,按 Asia/Shanghai(UTC+8)解释
|
||||
formFields: Record<string, string>;
|
||||
}
|
||||
|
||||
@@ -248,7 +248,7 @@ export interface UrdfUploadSignature {
|
||||
batchCode: string;
|
||||
mainRelativePath: string;
|
||||
uploadUrl: string;
|
||||
expiresAt: UtcDateTime; // 无时区后缀,按 UTC 解释
|
||||
expiresAt: ShanghaiDateTime; // 无时区后缀,按 Asia/Shanghai(UTC+8)解释
|
||||
files: Array<{
|
||||
relativePath: string;
|
||||
objectKey: string;
|
||||
@@ -296,7 +296,7 @@ export interface Comment {
|
||||
commentCode: string;
|
||||
author: PublicUser;
|
||||
content: string;
|
||||
createdAt: UtcDateTime;
|
||||
createdAt: ShanghaiDateTime;
|
||||
}
|
||||
```
|
||||
|
||||
@@ -543,7 +543,7 @@ data 示例中 image 仅展示格式前缀,实际值为完整图片:
|
||||
}
|
||||
```
|
||||
|
||||
签名有效期为 5 分钟;策略绑定 Bucket、完整对象 key、Content-Type、1 字节~5 MiB 的大小范围和成功状态码 200。文件类型按声明的 MIME 约束,后端不读取或解码图片。对象路径由后端生成,日期使用 UTC:test 为 `vibemake_dev/project-covers/{userCode}/{yyyyMMdd}/{随机编码}.{扩展名}`,prod 为 `vibemake/project-covers/...`。不要修改 formFields、对象路径或上传类型。
|
||||
签名有效期为 5 分钟;策略绑定 Bucket、完整对象 key、Content-Type、1 字节~5 MiB 的大小范围和成功状态码 200。文件类型按声明的 MIME 约束,后端不读取或解码图片。对象路径由后端生成,日期使用 Asia/Shanghai:test 为 `vibemake_dev/project-covers/{userCode}/{yyyyMMdd}/{随机编码}.{扩展名}`,prod 为 `vibemake/project-covers/...`。不要修改 formFields、对象路径或上传类型。
|
||||
|
||||
### 浏览器直传与保存项目
|
||||
|
||||
@@ -1471,14 +1471,14 @@ async function downloadWorkspaceFile(projectCode: string, path: string, token: s
|
||||
}
|
||||
```
|
||||
|
||||
### UTC 时间解析
|
||||
### 上海时间解析
|
||||
|
||||
只对项目、评论中不带时区的 UTC 字段使用这个函数;历史 authorDate 已带时区时按其原值解析。
|
||||
对项目、评论、上传过期时间等不带时区的上海时间字段使用这个函数;历史 authorDate 已带时区时按其原值解析。前端与后端需同时切换,旧版补 `Z` 的解析方式会多显示 8 小时。
|
||||
|
||||
```typescript
|
||||
function parseUtcTime(value: UtcDateTime): Date {
|
||||
function parseShanghaiTime(value: ShanghaiDateTime): Date {
|
||||
const hasTimezone = /(?:Z|[+-]\d{2}:\d{2})$/i.test(value);
|
||||
return new Date(hasTimezone ? value : `${value}Z`);
|
||||
return new Date(hasTimezone ? value : `${value}+08:00`);
|
||||
}
|
||||
```
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime
|
||||
import fcntl
|
||||
import getpass
|
||||
import json
|
||||
@@ -17,6 +17,7 @@ import tempfile
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import quote, urlencode, urlsplit, urlunsplit
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
|
||||
class MigrationError(Exception):
|
||||
@@ -28,7 +29,7 @@ class MigrationError(Exception):
|
||||
|
||||
|
||||
def timestamp() -> str:
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
return datetime.now(ZoneInfo("Asia/Shanghai")).isoformat()
|
||||
|
||||
|
||||
def name_segment(value: str) -> str:
|
||||
|
||||
@@ -17,7 +17,7 @@ spring:
|
||||
# 文件合计最多 200 MiB,额外预留 2 MiB 表单开销。
|
||||
max-request-size: 202MB
|
||||
jackson:
|
||||
time-zone: UTC
|
||||
time-zone: Asia/Shanghai
|
||||
data:
|
||||
redis:
|
||||
host: ${REDIS_HOST:localhost}
|
||||
|
||||
@@ -17,7 +17,7 @@ spring:
|
||||
# 文件合计最多 200 MiB,额外预留 2 MiB 表单开销。
|
||||
max-request-size: 202MB
|
||||
jackson:
|
||||
time-zone: UTC
|
||||
time-zone: Asia/Shanghai
|
||||
data:
|
||||
redis:
|
||||
host: ${REDIS_HOST:localhost}
|
||||
|
||||
+4
-3
@@ -13,6 +13,7 @@ import com.linkerbot.vibemake.service.gitea.GiteaClient.RemoteRepository;
|
||||
import com.linkerbot.vibemake.service.mapper.ProjectMapper;
|
||||
import com.linkerbot.vibemake.service.oss.OssResourcePaths;
|
||||
import com.linkerbot.vibemake.service.support.ProjectInputs;
|
||||
import com.linkerbot.vibemake.service.support.ProjectSupport;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -116,7 +117,7 @@ public final class ImportCoordinator {
|
||||
e -> {
|
||||
if (e.reservedAt == null)
|
||||
e.reservedAt =
|
||||
LocalDateTime.now(Clock.systemUTC())
|
||||
ProjectSupport.now()
|
||||
.truncatedTo(ChronoUnit.MILLIS)
|
||||
.toString();
|
||||
e.phase = Phase.RESERVING;
|
||||
@@ -258,7 +259,7 @@ public final class ImportCoordinator {
|
||||
|
||||
project.setGiteaRepoId(remote.id());
|
||||
project.setRepoStatus("READY");
|
||||
project.setUpdatedAt(LocalDateTime.now(Clock.systemUTC()));
|
||||
project.setUpdatedAt(ProjectSupport.now());
|
||||
if (projects.updateById(project) != 1)
|
||||
throw new ImportFailure("DATABASE_UPDATE_FAILED", "项目仓库关联写入失败");
|
||||
store.phase(entry, Phase.LINKED);
|
||||
@@ -317,7 +318,7 @@ public final class ImportCoordinator {
|
||||
}
|
||||
if (owned && project != null && !"READY".equals(project.getRepoStatus())) {
|
||||
project.setRepoStatus(review ? "CREATING" : "FAILED");
|
||||
project.setUpdatedAt(LocalDateTime.now(Clock.systemUTC()));
|
||||
project.setUpdatedAt(ProjectSupport.now());
|
||||
try {
|
||||
projects.updateById(project);
|
||||
} catch (RuntimeException databaseFailure) {
|
||||
|
||||
@@ -69,6 +69,8 @@ public final class ImportModels {
|
||||
|
||||
public static final class Manifest {
|
||||
public int version = 1;
|
||||
// 旧清单未声明时区,其 reservedAt 按 UTC 迁移。
|
||||
public String timeZone;
|
||||
public String fingerprint;
|
||||
public String ownerUserCode;
|
||||
public String giteaBaseUrl;
|
||||
|
||||
@@ -3,16 +3,22 @@ package com.linkerbot.vibemake.importer;
|
||||
import static com.linkerbot.vibemake.importer.ImportModels.*;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.vibemake.service.support.ProjectSupport;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.FileLock;
|
||||
import java.nio.file.*;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
import java.util.*;
|
||||
import java.util.function.Consumer;
|
||||
|
||||
public final class StateStore implements AutoCloseable {
|
||||
private static final Logger log = LoggerFactory.getLogger(StateStore.class);
|
||||
private final Path directory;
|
||||
private final ObjectMapper json = new ObjectMapper().findAndRegisterModules();
|
||||
private final FileChannel channel;
|
||||
@@ -49,8 +55,10 @@ public final class StateStore implements AutoCloseable {
|
||||
.equals(manifest.entries.stream().map(e -> e.candidate).toList())
|
||||
|| !data.excluded().equals(manifest.excluded))
|
||||
throw new ImportFailure("BATCH_CHANGED", "Excel 或清单内容已变化,请使用新的状态目录");
|
||||
migrateTimeZone();
|
||||
} else {
|
||||
manifest = new Manifest();
|
||||
manifest.timeZone = ProjectSupport.TIME_ZONE.getId();
|
||||
manifest.fingerprint = data.fingerprint();
|
||||
manifest.excluded.addAll(data.excluded());
|
||||
data.candidates().forEach(c -> manifest.entries.add(new Entry(c)));
|
||||
@@ -63,6 +71,24 @@ public final class StateStore implements AutoCloseable {
|
||||
}
|
||||
}
|
||||
|
||||
private void migrateTimeZone() throws IOException {
|
||||
String targetZone = ProjectSupport.TIME_ZONE.getId();
|
||||
if (targetZone.equals(manifest.timeZone)) return;
|
||||
if (manifest.timeZone != null)
|
||||
throw new ImportFailure("BATCH_TIME_ZONE_MISMATCH", "导入清单时区不受支持,请人工核对");
|
||||
int converted = 0;
|
||||
for (Entry entry : manifest.entries) {
|
||||
if (entry.reservedAt == null) continue;
|
||||
entry.reservedAt = ProjectSupport.fromInstant(
|
||||
LocalDateTime.parse(entry.reservedAt).toInstant(ZoneOffset.UTC)).toString();
|
||||
converted++;
|
||||
}
|
||||
manifest.timeZone = targetZone;
|
||||
save();
|
||||
log.info("导入清单时间迁移完成 sourceTimeZone=UTC targetTimeZone={} convertedEntries={}",
|
||||
targetZone, converted);
|
||||
}
|
||||
|
||||
public synchronized void update(Entry entry, Consumer<Entry> change) throws IOException {
|
||||
change.accept(entry);
|
||||
save();
|
||||
@@ -90,6 +116,7 @@ public final class StateStore implements AutoCloseable {
|
||||
phase.name(), manifest.entries.stream().filter(e -> e.phase == phase).count());
|
||||
Map<String, Object> report = new LinkedHashMap<>();
|
||||
report.put("fingerprint", manifest.fingerprint);
|
||||
report.put("timeZone", manifest.timeZone);
|
||||
report.put("candidateCount", manifest.entries.size());
|
||||
report.put("excludedCount", manifest.excluded.size());
|
||||
report.put("counts", counts);
|
||||
|
||||
+2
-2
@@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.linkerbot.vibemake.service.config.OssProperties;
|
||||
import com.linkerbot.vibemake.service.oss.OssResourcePaths;
|
||||
import com.linkerbot.vibemake.service.support.ProjectSupport;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
@@ -11,7 +12,6 @@ import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.time.Instant;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
@@ -100,7 +100,7 @@ public final class CoverMigrationApplication {
|
||||
long unique = candidates.stream().map(candidate -> candidate.originalUrl().trim()).distinct().count();
|
||||
System.out.printf("封面迁移预览 environmentRoot=%s candidateProjects=%d uniqueUrls=%d execute=%s%n",
|
||||
oss.getRootDirectory(), candidates.size(), unique, options.execute());
|
||||
Path run = options.reportDirectory().resolve(Instant.now().toString().replace(':', '-') + "-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
Path run = options.reportDirectory().resolve(ProjectSupport.now().toString().replace(':', '-') + "-" + UUID.randomUUID().toString().substring(0, 8));
|
||||
Files.createDirectories(run);
|
||||
restrict(run, "rwx------");
|
||||
ObjectMapper json = new ObjectMapper();
|
||||
|
||||
@@ -6,7 +6,7 @@ spring:
|
||||
init:
|
||||
mode: never
|
||||
datasource:
|
||||
url: ${DB_URL:jdbc:mysql://localhost:3306/vibemake?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC}
|
||||
url: ${DB_URL:jdbc:mysql://localhost:3306/vibemake?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai}
|
||||
username: ${DB_USERNAME:root}
|
||||
password: ${DB_PASSWORD:}
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
|
||||
+7
@@ -180,9 +180,16 @@ class ImportCoordinatorTest {
|
||||
|
||||
@Test
|
||||
void migrationBindsShortCodeAdaptsMasterAndPublishesWithoutEmptyRepository() throws Exception {
|
||||
Instant before = Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MILLIS);
|
||||
worker(projects, service).run(entry);
|
||||
Instant after = Instant.now();
|
||||
assertThat(entry.phase).isEqualTo(Phase.PUBLISHED);
|
||||
Project project = service.published(entry.projectCode);
|
||||
ZoneId shanghai = ZoneId.of("Asia/Shanghai");
|
||||
assertThat(project.getCreatedAt().atZone(shanghai).toInstant()).isBetween(before, after);
|
||||
assertThat(project.getUpdatedAt().atZone(shanghai).toInstant()).isBetween(before, after);
|
||||
assertThat(project.getPublishedAt().atZone(shanghai).toInstant()).isBetween(before, after);
|
||||
assertThat(LocalDateTime.parse(entry.reservedAt)).isEqualTo(project.getCreatedAt());
|
||||
assertThat(project.getProjectCode()).isEqualTo(entry.projectCode).hasSize(12);
|
||||
assertThat(project.getGiteaRepoId()).isEqualTo(77L);
|
||||
assertThat(project.getPublishedCommitSha()).isEqualTo(SHA);
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.linkerbot.vibemake.importer;
|
||||
|
||||
import static com.linkerbot.vibemake.importer.ImportModels.*;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.List;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
class StateStoreTest {
|
||||
@TempDir Path directory;
|
||||
private final ObjectMapper json = new ObjectMapper();
|
||||
private final Candidate candidate = new Candidate("sheet", 1, "项目", "https://github.com/example/robot",
|
||||
"简介", "GENERAL", null);
|
||||
private final WorkbookData data = new WorkbookData("fingerprint", List.of(candidate), List.of());
|
||||
|
||||
@Test
|
||||
void newStateAndReportDeclareShanghaiTimeZone() throws Exception {
|
||||
try (StateStore store = new StateStore(directory, data)) {
|
||||
assertThat(store.manifest.timeZone).isEqualTo("Asia/Shanghai");
|
||||
store.report();
|
||||
}
|
||||
assertThat(json.readTree(Files.readString(directory.resolve("report.json")))
|
||||
.path("timeZone").asText()).isEqualTo("Asia/Shanghai");
|
||||
}
|
||||
|
||||
@Test
|
||||
void legacyUtcReservationsAreMigratedAtomicallyAndOnlyOnce() throws Exception {
|
||||
Manifest legacy = new Manifest();
|
||||
legacy.fingerprint = data.fingerprint();
|
||||
Entry reserved = new Entry(candidate);
|
||||
reserved.reservedAt = "2026-12-31T16:00:00.123";
|
||||
legacy.entries.add(reserved);
|
||||
json.writeValue(directory.resolve("manifest.json").toFile(), legacy);
|
||||
|
||||
try (StateStore store = new StateStore(directory, data)) {
|
||||
assertThat(store.manifest.entries.getFirst().reservedAt).isEqualTo("2027-01-01T00:00:00.123");
|
||||
assertThat(store.manifest.timeZone).isEqualTo("Asia/Shanghai");
|
||||
}
|
||||
try (StateStore reopened = new StateStore(directory, data)) {
|
||||
assertThat(reopened.manifest.entries.getFirst().reservedAt).isEqualTo("2027-01-01T00:00:00.123");
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void unsupportedStateTimeZonesFailBeforeChangingProgress() throws Exception {
|
||||
try (StateStore store = new StateStore(directory, data)) {
|
||||
store.manifest.timeZone = "America/New_York";
|
||||
store.save();
|
||||
}
|
||||
String before = Files.readString(directory.resolve("manifest.json"));
|
||||
assertThatThrownBy(() -> new StateStore(directory, data))
|
||||
.isInstanceOfSatisfying(ImportFailure.class,
|
||||
error -> assertThat(error.code()).isEqualTo("BATCH_TIME_ZONE_MISMATCH"));
|
||||
assertThat(Files.readString(directory.resolve("manifest.json"))).isEqualTo(before);
|
||||
}
|
||||
}
|
||||
+2
-3
@@ -6,6 +6,7 @@ import com.linkerbot.vibemake.bean.entity.User;
|
||||
import com.linkerbot.vibemake.common.*;
|
||||
import com.linkerbot.vibemake.service.UserService;
|
||||
import com.linkerbot.vibemake.service.mapper.UserMapper;
|
||||
import com.linkerbot.vibemake.service.support.ProjectSupport;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
@@ -14,8 +15,6 @@ import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Locale;
|
||||
|
||||
@Service
|
||||
@@ -46,7 +45,7 @@ public class UserServiceImpl implements UserService {
|
||||
candidate.setEmail(normalizedEmail);
|
||||
candidate.setNickname("用户_" + candidate.getUserCode().substring(0, 8));
|
||||
candidate.setStatus("ACTIVE");
|
||||
candidate.setCreatedAt(LocalDateTime.now(Clock.systemUTC()));
|
||||
candidate.setCreatedAt(ProjectSupport.now());
|
||||
candidate.setUpdatedAt(candidate.getCreatedAt());
|
||||
try {
|
||||
users.insert(candidate);
|
||||
|
||||
+6
-2
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.vibemake.bean.Contracts.CoverUploadSignature;
|
||||
import com.linkerbot.vibemake.common.Codes;
|
||||
import com.linkerbot.vibemake.service.config.OssProperties;
|
||||
import com.linkerbot.vibemake.service.support.ProjectSupport;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.time.*;
|
||||
@@ -24,6 +25,9 @@ public class OssPostSigner {
|
||||
public static final long MAX_FILE_BYTES = 5L * 1024 * 1024;
|
||||
private static final Duration VALIDITY = Duration.ofMinutes(5);
|
||||
private static final String VERSION = "OSS4-HMAC-SHA256";
|
||||
private static final DateTimeFormatter BUSINESS_DATE =
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ProjectSupport.TIME_ZONE);
|
||||
// OSS V4 协议中的凭据日期、请求时间和策略过期时间必须使用 UTC。
|
||||
private static final DateTimeFormatter DATE =
|
||||
DateTimeFormatter.ofPattern("yyyyMMdd").withZone(ZoneOffset.UTC);
|
||||
private static final DateTimeFormatter TIMESTAMP =
|
||||
@@ -49,7 +53,7 @@ public class OssPostSigner {
|
||||
|
||||
public CoverUploadSignature sign(String userCode, String contentType, String extension) {
|
||||
String key = properties.getRootDirectory() + "/project-covers/" + userCode + "/"
|
||||
+ DATE.format(clock.instant()) + "/" + Codes.next() + "." + extension;
|
||||
+ BUSINESS_DATE.format(clock.instant()) + "/" + Codes.next() + "." + extension;
|
||||
SignedPost post = post(key, contentType, 1, MAX_FILE_BYTES, VALIDITY, false);
|
||||
return new CoverUploadSignature(properties.uploadUrl(), key,
|
||||
resourcePaths.publicUrl(key), post.expiresAt(), post.formFields());
|
||||
@@ -105,7 +109,7 @@ public class OssPostSigner {
|
||||
fields.put("x-oss-forbid-overwrite", "true");
|
||||
fields.put("x-oss-content-type", contentType);
|
||||
}
|
||||
return new SignedPost(LocalDateTime.ofInstant(expiration, ZoneOffset.UTC), Map.copyOf(fields));
|
||||
return new SignedPost(ProjectSupport.fromInstant(expiration), Map.copyOf(fields));
|
||||
} catch (JsonProcessingException | GeneralSecurityException error) {
|
||||
log.error("OSS 签名生成失败 objectKey={} region={} errorType={}",
|
||||
key, properties.getRegion(), error.getClass().getSimpleName());
|
||||
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package com.linkerbot.vibemake.service.oss;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.vibemake.bean.Contracts.ResourceFile;
|
||||
import com.linkerbot.vibemake.bean.Contracts.ResourceFileView;
|
||||
import com.linkerbot.vibemake.common.BusinessException;
|
||||
import com.linkerbot.vibemake.common.FilePaths;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/** 仅处理资源路径和清单,不依赖 OSS 上传配置、签名或客户端。 */
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ProjectResourceFiles {
|
||||
public static final long OSS_MAX_FILE_BYTES = 5L * 1024 * 1024 * 1024;
|
||||
private static final Logger log = LoggerFactory.getLogger(ProjectResourceFiles.class);
|
||||
private static final TypeReference<List<ResourceFile>> FILES_TYPE = new TypeReference<>() {};
|
||||
private final ObjectMapper json;
|
||||
private final OssResourcePaths paths;
|
||||
|
||||
public void validate(String prefix, ProjectResourceType type, List<ResourceFile> files) {
|
||||
if (files == null || files.isEmpty()) throw BusinessException.badRequest("资源文件清单不能为空");
|
||||
if (type.singleFile() && files.size() != 1)
|
||||
throw BusinessException.badRequest("该资源类型必须且只能上传一个文件");
|
||||
Set<String> seen = new HashSet<>();
|
||||
for (ResourceFile file : files) {
|
||||
if (file == null || file.sizeBytes() == null || file.sizeBytes() < 0)
|
||||
throw BusinessException.badRequest("文件大小不合法");
|
||||
if (file.sizeBytes() > OSS_MAX_FILE_BYTES)
|
||||
throw new BusinessException(413, "RESOURCE_FILE_TOO_LARGE", "OSS 表单直传单文件不能超过 5 GB");
|
||||
String path = FilePaths.file(file.relativePath());
|
||||
if (type.singleFile() && path.contains("/"))
|
||||
throw BusinessException.badRequest("单文件资源请直接提交文件名");
|
||||
if (!path.toLowerCase(Locale.ROOT).endsWith(type.extension()))
|
||||
throw BusinessException.badRequest("该资源类型只接受 " + type.extension() + " 文件");
|
||||
if (!seen.add(path)) throw BusinessException.badRequest("上传路径不能重复");
|
||||
String key = paths.objectKey(prefix + path);
|
||||
if ((prefix + path).length() > 512 || key.getBytes(StandardCharsets.UTF_8).length > 1023)
|
||||
throw BusinessException.badRequest("资源文件对象路径过长");
|
||||
}
|
||||
}
|
||||
|
||||
public String manifest(List<ResourceFile> files) {
|
||||
try {
|
||||
return json.writeValueAsString(files);
|
||||
} catch (JsonProcessingException error) {
|
||||
throw new IllegalStateException("资源文件清单序列化失败", error);
|
||||
}
|
||||
}
|
||||
|
||||
public List<ResourceFileView> fileViews(String prefix, String manifest, ProjectResourceType type) {
|
||||
if (prefix == null || prefix.isEmpty()) return List.of();
|
||||
// Fork 可以引用源项目批次;这里校验资源命名空间,不要求目录属于当前项目。
|
||||
String storagePrefix = paths.storagePath(prefix);
|
||||
if (!storagePrefix.matches("/project-resources/(?:[a-z0-9]{12}|[a-z0-9]{32})/"
|
||||
+ type.code() + "/[a-f0-9]{32}/")) throw invalidManifest();
|
||||
try {
|
||||
List<ResourceFile> files = json.readValue(manifest, FILES_TYPE);
|
||||
validate(storagePrefix, type, files);
|
||||
List<ResourceFileView> result = new ArrayList<>();
|
||||
for (ResourceFile file : files)
|
||||
result.add(new ResourceFileView(file.relativePath(), file.sizeBytes(),
|
||||
paths.publicUrl(storagePrefix + file.relativePath())));
|
||||
return List.copyOf(result);
|
||||
} catch (JsonProcessingException | IllegalArgumentException | BusinessException error) {
|
||||
log.error("项目资源文件清单读取失败 resourceType={} prefix={} errorType={}",
|
||||
type.code(), storagePrefix, error.getClass().getSimpleName());
|
||||
throw invalidManifest();
|
||||
}
|
||||
}
|
||||
|
||||
private BusinessException invalidManifest() {
|
||||
return new BusinessException(500, "RESOURCE_MANIFEST_INVALID", "项目资源文件清单异常");
|
||||
}
|
||||
}
|
||||
+10
-2
@@ -2,15 +2,23 @@ package com.linkerbot.vibemake.service.support;
|
||||
|
||||
import com.linkerbot.vibemake.common.BusinessException;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
/** 项目、文件和互动服务共用的时间与分页约定。 */
|
||||
public final class ProjectSupport {
|
||||
public static final ZoneId TIME_ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
private ProjectSupport() {}
|
||||
|
||||
/** 业务数据库和接口统一使用上海时间,不依赖 JVM 默认时区。 */
|
||||
public static LocalDateTime now() {
|
||||
return LocalDateTime.now(Clock.systemUTC());
|
||||
return fromInstant(Instant.now());
|
||||
}
|
||||
|
||||
public static LocalDateTime fromInstant(Instant instant) {
|
||||
return LocalDateTime.ofInstant(instant, TIME_ZONE);
|
||||
}
|
||||
|
||||
public static void pageCheck(long page, long size) {
|
||||
|
||||
+14
@@ -15,11 +15,25 @@ import org.mockito.ArgumentCaptor;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
|
||||
import java.util.List;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
|
||||
class UserServiceImplTest {
|
||||
private final UserMapper users = mock(UserMapper.class);
|
||||
private final UserServiceImpl service = new UserServiceImpl(users);
|
||||
|
||||
@Test
|
||||
void registrationPersistsShanghaiCreationAndUpdateTime() {
|
||||
Instant before = Instant.now();
|
||||
User created = service.login("new@example.com");
|
||||
Instant after = Instant.now();
|
||||
|
||||
assertThat(created.getCreatedAt().atZone(ZoneId.of("Asia/Shanghai")).toInstant())
|
||||
.isBetween(before, after);
|
||||
assertThat(created.getUpdatedAt()).isEqualTo(created.getCreatedAt());
|
||||
verify(users).insert(created);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"USER", "ADMIN"})
|
||||
void activeCommunityAccountsCanLogInWithoutAPassword(String role) {
|
||||
|
||||
+5
-5
@@ -38,16 +38,16 @@ class OssPostSignerTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void bindsExactObjectAndMimeWithUtcDatesAndFiveMinuteExpiry() throws Exception {
|
||||
void usesShanghaiBusinessDatesAndExpiryWhileKeepingOssProtocolInUtc() throws Exception {
|
||||
OssProperties properties = properties();
|
||||
Clock clock = Clock.fixed(Instant.parse("2026-10-14T23:58:30.123456789Z"), ZoneId.of("Asia/Shanghai"));
|
||||
OssPostSigner signer = new OssPostSigner(properties, json, clock);
|
||||
String user = "1".repeat(32);
|
||||
CoverUploadSignature result = signer.sign(user, "image/png", "png");
|
||||
assertThat(result.uploadUrl()).isEqualTo("https://examplebucket.oss-cn-hangzhou.aliyuncs.com");
|
||||
assertThat(result.objectKey()).matches("vibemake_dev/project-covers/" + user + "/20261014/[a-f0-9]{32}\\.png");
|
||||
assertThat(result.objectKey()).matches("vibemake_dev/project-covers/" + user + "/20261015/[a-f0-9]{32}\\.png");
|
||||
assertThat(result.coverUrl()).isEqualTo(result.uploadUrl() + "/" + result.objectKey());
|
||||
assertThat(result.expiresAt()).isEqualTo(LocalDateTime.parse("2026-10-15T00:03:30.123"));
|
||||
assertThat(result.expiresAt()).isEqualTo(LocalDateTime.parse("2026-10-15T08:03:30.123"));
|
||||
assertThat(result.formFields()).containsEntry("key", result.objectKey())
|
||||
.containsEntry("content-type", "image/png")
|
||||
.containsEntry("success_action_status", "200")
|
||||
@@ -76,7 +76,7 @@ class OssPostSignerTest {
|
||||
OssPostSigner signer = new OssPostSigner(properties(), json, clock);
|
||||
String key = "vibemake_dev/urdf/7m4k9x2p8q6r/" + "a".repeat(32) + "/urdf/机械 臂.URDF";
|
||||
OssPostSigner.SignedPost post = signer.signObject(key, "application/xml", 1234);
|
||||
assertThat(post.expiresAt()).isEqualTo(LocalDateTime.parse("2026-10-15T00:13:30"));
|
||||
assertThat(post.expiresAt()).isEqualTo(LocalDateTime.parse("2026-10-15T08:13:30"));
|
||||
JsonNode policy = json.readTree(Base64.getDecoder().decode(post.formFields().get("policy")));
|
||||
List<Object> conditions = json.convertValue(policy.path("conditions"), new TypeReference<>() {});
|
||||
assertThat(conditions).contains(List.of("eq", "$key", key),
|
||||
@@ -106,7 +106,7 @@ class OssPostSignerTest {
|
||||
String key = "vibemake_dev/project-resources/7m4k9x2p8q6r/model-glb/" + "a".repeat(32) + "/a.glb";
|
||||
long bytes = ProjectResources.OSS_MAX_FILE_BYTES;
|
||||
OssPostSigner.SignedPost post = signer.signObject(key, "model/gltf-binary", bytes, Duration.ofHours(1));
|
||||
assertThat(post.expiresAt()).isEqualTo(LocalDateTime.parse("2026-10-15T00:58:30"));
|
||||
assertThat(post.expiresAt()).isEqualTo(LocalDateTime.parse("2026-10-15T08:58:30"));
|
||||
JsonNode policy = json.readTree(Base64.getDecoder().decode(post.formFields().get("policy")));
|
||||
assertThat(policy.path("conditions").toString()).contains("[\"content-length-range\",5368709120,5368709120]");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user