From 784bb0a965da82d2d7a35c246c27586ac09bf14a Mon Sep 17 00:00:00 2001 From: xiaowang Date: Fri, 5 Jun 2026 12:52:38 +0800 Subject: [PATCH] =?UTF-8?q?=E5=8A=9F=E8=83=BD=EF=BC=9A=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=20OSS=20=E5=A4=87=E4=BB=BD=E5=92=8C=E4=BA=A4=E6=8E=A5=E6=96=87?= =?UTF-8?q?=E6=A1=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增阿里云 OSS 异步备份、重试调度和文件访问签名 URL 回退。 扩展文件存储元数据表结构,并更新作品、店铺、评论、消息和美甲师流程的图片 URL 解析。 新增面向后续 YumiNail 会话的低 token 交接文档。 --- .idea/compiler.xml | 1 - YumiNail-Core/pom.xml | 7 + .../yuminailcore/config/RabbitMQConfig.java | 60 ++--- .../impl/NailArtistInfoServiceImpl.java | 6 +- .../controller/front/CommentController.java | 7 + .../service/impl/CommentServiceImpl.java | 13 +- .../modules/file/config/AliyunOssConfig.java | 35 +++ .../front/FrontendFileController.java | 18 +- .../front/ObjectStorageFileController.java | 21 +- .../file/dto/ObjectStorageFileDTO.java | 22 ++ .../file/dto/OssBackupUploadMessage.java | 13 ++ .../file/entity/ObjectStorageFileDO.java | 33 +++ .../file/mq/OssBackupMessageListener.java | 29 +++ .../file/mq/OssBackupMessagePublisher.java | 31 +++ .../scheduler/OssBackupRetryScheduler.java | 44 ++++ .../file/service/AliyunOssService.java | 10 + .../service/ObjectStorageFileService.java | 2 + .../file/service/OssBackupService.java | 6 + .../service/impl/AliyunOssServiceImpl.java | 65 ++++++ .../impl/ObjectStorageFileServiceImpl.java | 59 ++++- .../service/impl/OssBackupServiceImpl.java | 88 +++++++ .../file/support/ObjectStorageUrlSupport.java | 216 ++++++++++++++---- .../modules/file/vo/ObjectStorageFileVO.java | 22 ++ .../impl/SystemMessageServiceImpl.java | 2 +- .../service/impl/ProductServiceImpl.java | 4 +- .../shop/service/impl/ShopServiceImpl.java | 2 +- .../src/main/resources/files/YumiNail.sql | 34 +++ .../impl/NailArtistInfoServiceImplTest.java | 6 + .../file/FileOssBackupConfigurationTest.java | 25 ++ .../front/FrontendFileControllerTest.java | 25 +- .../OssBackupRetrySchedulerTest.java | 49 ++++ .../ObjectStorageFileServiceImplTest.java | 69 ++++++ .../impl/OssBackupServiceImplTest.java | 93 ++++++++ .../support/ObjectStorageUrlSupportTest.java | 76 +++++- .../service/impl/ProductServiceImplTest.java | 5 + .../service/impl/ShopServiceImplTest.java | 2 + .../support/YumiNailSqlSchemaTest.java | 25 ++ artifacts/real-upload-signed-preview.png | Bin 0 -> 9607 bytes docx/handoff/CORE-MODULES.md | 92 ++++++++ docx/handoff/CURRENT-STATE.md | 68 ++++++ docx/handoff/HANDOFF-BOOT.md | 99 ++++++++ docx/handoff/NEXT-SESSION-PROMPT.md | 8 + docx/handoff/PROJECT-MAP.md | 116 ++++++++++ docx/handoff/RISK-REGISTER.md | 99 ++++++++ docx/handoff/TASK-PLAYBOOKS.md | 144 ++++++++++++ scripts/sql/init/YumiNail.sql | 34 +++ 46 files changed, 1742 insertions(+), 143 deletions(-) create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/config/AliyunOssConfig.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/OssBackupUploadMessage.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessageListener.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessagePublisher.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/scheduler/OssBackupRetryScheduler.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/AliyunOssService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/OssBackupService.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/AliyunOssServiceImpl.java create mode 100644 YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/OssBackupServiceImpl.java create mode 100644 YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/FileOssBackupConfigurationTest.java create mode 100644 YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/scheduler/OssBackupRetrySchedulerTest.java create mode 100644 YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageFileServiceImplTest.java create mode 100644 YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/service/impl/OssBackupServiceImplTest.java create mode 100644 artifacts/real-upload-signed-preview.png create mode 100644 docx/handoff/CORE-MODULES.md create mode 100644 docx/handoff/CURRENT-STATE.md create mode 100644 docx/handoff/HANDOFF-BOOT.md create mode 100644 docx/handoff/NEXT-SESSION-PROMPT.md create mode 100644 docx/handoff/PROJECT-MAP.md create mode 100644 docx/handoff/RISK-REGISTER.md create mode 100644 docx/handoff/TASK-PLAYBOOKS.md diff --git a/.idea/compiler.xml b/.idea/compiler.xml index dc34c7f5..d7810c91 100644 --- a/.idea/compiler.xml +++ b/.idea/compiler.xml @@ -9,7 +9,6 @@ - diff --git a/YumiNail-Core/pom.xml b/YumiNail-Core/pom.xml index df408bea..6444623d 100644 --- a/YumiNail-Core/pom.xml +++ b/YumiNail-Core/pom.xml @@ -200,6 +200,13 @@ 8.5.7 + + + com.aliyun.oss + aliyun-sdk-oss + 3.18.5 + + org.projectlombok diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RabbitMQConfig.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RabbitMQConfig.java index 71c82516..b392f914 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RabbitMQConfig.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RabbitMQConfig.java @@ -9,61 +9,51 @@ import org.springframework.amqp.support.converter.MessageConverter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -/** - * RabbitMQ配置类 - * 配置交换机、队列以及消息转换器 - * - * @author xiaowang - * @date 2026-02-12 - */ @Configuration public class RabbitMQConfig { - /** - * 配置消息转换器为JSON格式 - */ + public static final String EXAMPLE_QUEUE = "yuminail.example.queue"; + public static final String EXAMPLE_EXCHANGE = "yuminail.example.exchange"; + public static final String EXAMPLE_ROUTING_KEY = "yuminail.example.routing.key"; + + public static final String FILE_OSS_BACKUP_EXCHANGE = "yuminail.file.oss.backup.exchange"; + public static final String FILE_OSS_BACKUP_QUEUE = "yuminail.file.oss.backup.queue"; + public static final String FILE_OSS_BACKUP_ROUTING_KEY = "yuminail.file.oss.backup"; + @Bean public MessageConverter jsonMessageConverter() { return new Jackson2JsonMessageConverter(); } - // 示例队列和交换机配置,方便后续扩展 - public static final String EXAMPLE_QUEUE = "yuminail.example.queue"; - /** - * Purpose: EXAMPLE_EXCHANGE supports RabbitMQConfig.java by holding or executing the example exchange business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String EXAMPLE_EXCHANGE = "yuminail.example.exchange"; - /** - * Purpose: EXAMPLE_ROUTING_KEY supports RabbitMQConfig.java by holding or executing the example routing key business role. - * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. - */ - public static final String EXAMPLE_ROUTING_KEY = "yuminail.example.routing.key"; - @Bean - /** - * Purpose: exampleQueue supports RabbitMQConfig.java by holding or executing the example queue business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ public Queue exampleQueue() { return new Queue(EXAMPLE_QUEUE, true); } @Bean - /** - * Purpose: exampleExchange supports RabbitMQConfig.java by holding or executing the example exchange business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ public DirectExchange exampleExchange() { return new DirectExchange(EXAMPLE_EXCHANGE); } @Bean - /** - * Purpose: exampleBinding supports RabbitMQConfig.java by holding or executing the example binding business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ public Binding exampleBinding() { return BindingBuilder.bind(exampleQueue()).to(exampleExchange()).with(EXAMPLE_ROUTING_KEY); } + + @Bean + public Queue fileOssBackupQueue() { + return new Queue(FILE_OSS_BACKUP_QUEUE, true); + } + + @Bean + public DirectExchange fileOssBackupExchange() { + return new DirectExchange(FILE_OSS_BACKUP_EXCHANGE, true, false); + } + + @Bean + public Binding fileOssBackupBinding() { + return BindingBuilder.bind(fileOssBackupQueue()) + .to(fileOssBackupExchange()) + .with(FILE_OSS_BACKUP_ROUTING_KEY); + } } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/artist/service/impl/NailArtistInfoServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/artist/service/impl/NailArtistInfoServiceImpl.java index b4de30ec..c23cdac8 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/artist/service/impl/NailArtistInfoServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/artist/service/impl/NailArtistInfoServiceImpl.java @@ -22,6 +22,7 @@ import com.xiaowang.yuminailcore.modules.shop.mapper.ShopMapper; import com.xiaowang.yuminailcore.modules.user.mapper.UserMapper; import com.xiaowang.yuminailcore.modules.artist.service.NailArtistInfoService; import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService; +import com.xiaowang.yuminailcore.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.yuminailcore.modules.shop.support.UserShopBindingSupport; import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistAvailabilityVO; import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistProfileVO; @@ -102,6 +103,9 @@ public class NailArtistInfoServiceImpl extends ServiceImpl im */ private final ProductMapper productMapper; private final ObjectStorageFileService objectStorageFileService; - private final MinioService minioService; private final ObjectStorageUrlSupport objectStorageUrlSupport; @Override @@ -561,16 +559,7 @@ public class CommentServiceImpl extends ServiceImpl im if (fileVO == null || !StringUtils.hasText(fileVO.getFileUrl())) { continue; } - String objectName = objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl()); - if (!StringUtils.hasText(objectName)) { - urls.add(fileVO.getFileUrl()); - continue; - } - try { - urls.add(minioService.getPresignedUrl(objectName, 60)); - } catch (Exception ignored) { - urls.add(fileVO.getFileUrl()); - } + urls.add(objectStorageUrlSupport.toAccessibleUrl(fileVO)); } return urls; } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/config/AliyunOssConfig.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/config/AliyunOssConfig.java new file mode 100644 index 00000000..d7bedb5a --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/config/AliyunOssConfig.java @@ -0,0 +1,35 @@ +package com.xiaowang.yuminailcore.modules.file.config; + +import com.aliyun.oss.OSS; +import com.aliyun.oss.OSSClientBuilder; +import lombok.Data; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.StringUtils; + +@Data +@Configuration +@ConfigurationProperties(prefix = "aliyun.oss") +public class AliyunOssConfig { + + private boolean enabled = false; + private String endpoint; + private String region; + private String bucketName = "fingertipdesigner"; + private String accessKeyId; + private String accessKeySecret; + private int signedUrlExpireMinutes = 30; + + @Bean(destroyMethod = "shutdown") + @ConditionalOnProperty(prefix = "aliyun.oss", name = "enabled", havingValue = "true") + public OSS aliyunOssClient() { + if (!StringUtils.hasText(endpoint) + || !StringUtils.hasText(accessKeyId) + || !StringUtils.hasText(accessKeySecret)) { + throw new IllegalStateException("Aliyun OSS is enabled but endpoint/accessKeyId/accessKeySecret is incomplete"); + } + return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/FrontendFileController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/FrontendFileController.java index 805e6ff8..0c4519d0 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/FrontendFileController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/FrontendFileController.java @@ -4,11 +4,11 @@ import com.xiaowang.yuminailcore.common.Result; import com.xiaowang.yuminailcore.modules.product.mapper.EffectDiagramMapper; import com.xiaowang.yuminailcore.modules.product.mapper.ProductMapper; import com.xiaowang.yuminailcore.modules.shop.mapper.ShopMapper; -import com.xiaowang.yuminailcore.modules.file.service.MinioService; import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService; import com.xiaowang.yuminailcore.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO; import lombok.RequiredArgsConstructor; +import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; @@ -24,7 +24,6 @@ import org.springframework.web.bind.annotation.RestController; @RequiredArgsConstructor public class FrontendFileController { private final ObjectStorageFileService objectStorageFileService; - private final MinioService minioService; private final ObjectStorageUrlSupport objectStorageUrlSupport; private final ProductMapper productMapper; private final ShopMapper shopMapper; @@ -46,12 +45,9 @@ public class FrontendFileController { return Result.error("文件不可公开访问"); } - String objectName = objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl()); - if (objectName == null || objectName.isEmpty()) { - return Result.success(fileVO.getFileUrl()); - } - - String signedUrl = minioService.getPresignedUrl(objectName, expiryTimeInMinutes); + String signedUrl = hasObjectStorageReference(fileVO) + ? objectStorageUrlSupport.getSignedUrlOrThrow(fileVO, expiryTimeInMinutes) + : fileVO.getFileUrl(); return Result.success(signedUrl); } catch (Exception e) { e.printStackTrace(); @@ -59,6 +55,12 @@ public class FrontendFileController { } } + private boolean hasObjectStorageReference(ObjectStorageFileVO fileVO) { + return StringUtils.hasText(fileVO.getObjectName()) + || StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getMinioUrl())) + || StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl())); + } + /** * Purpose: isPublicFileReference prevents arbitrary uploaded files from being exposed through the public signing endpoint. * Usage: call with a file id and keep mapper checks in sync with public content tables. diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/ObjectStorageFileController.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/ObjectStorageFileController.java index db13669f..3f3dac2e 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/ObjectStorageFileController.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/controller/front/ObjectStorageFileController.java @@ -110,6 +110,13 @@ public class ObjectStorageFileController { ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); dto.setFileName(originalFilename); dto.setFileUrl(fileUrl); + dto.setObjectName(objectName); + dto.setMinioUrl(fileUrl); + dto.setContentType(preparedUploadFile.getContentType()); + dto.setFileSize(preparedUploadFile.getFileSize()); + dto.setMinioUploadStatus(1); + dto.setOssUploadStatus(0); + dto.setOssRetryCount(0); dto.setStatus(1); Long fileId = objectStorageFileService.createObjectStorageFile(dto); @@ -153,6 +160,13 @@ public class ObjectStorageFileController { ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); dto.setFileName(originalFilename); dto.setFileUrl(fileUrl); + dto.setObjectName(objectName); + dto.setMinioUrl(fileUrl); + dto.setContentType(file.getContentType()); + dto.setFileSize(file.getSize()); + dto.setMinioUploadStatus(1); + dto.setOssUploadStatus(0); + dto.setOssRetryCount(0); dto.setStatus(1); Long fileId = objectStorageFileService.createObjectStorageFile(dto); @@ -175,12 +189,7 @@ public class ObjectStorageFileController { return Result.error("文件不存在"); } - String objectName = objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl()); - if (objectName == null || objectName.isEmpty()) { - return Result.error("文件 URL 格式错误"); - } - - String signedUrl = minioService.getPresignedUrl(objectName, expiryTimeInMinutes); + String signedUrl = objectStorageUrlSupport.getSignedUrlOrThrow(fileVO, expiryTimeInMinutes); return Result.success(signedUrl); } catch (Exception e) { e.printStackTrace(); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/ObjectStorageFileDTO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/ObjectStorageFileDTO.java index 5e8457ef..9c075c83 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/ObjectStorageFileDTO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/ObjectStorageFileDTO.java @@ -24,6 +24,28 @@ public class ObjectStorageFileDTO { */ private String fileUrl; + private String objectName; + + private String minioUrl; + + private String ossUrl; + + private String contentType; + + private Long fileSize; + + private Integer minioUploadStatus; + + private Integer ossUploadStatus; + + private Integer ossRetryCount; + + private String ossLastError; + + private LocalDateTime ossUploadedAt; + + private LocalDateTime ossLastRetryTime; + /** * 文件状态:1-可用,0-不可用,2-回收站 */ diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/OssBackupUploadMessage.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/OssBackupUploadMessage.java new file mode 100644 index 00000000..ac2ef12e --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/dto/OssBackupUploadMessage.java @@ -0,0 +1,13 @@ +package com.xiaowang.yuminailcore.modules.file.dto; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +@Data +@NoArgsConstructor +@AllArgsConstructor +public class OssBackupUploadMessage { + + private Long fileId; +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/entity/ObjectStorageFileDO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/entity/ObjectStorageFileDO.java index 1cd8857c..59424f05 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/entity/ObjectStorageFileDO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/entity/ObjectStorageFileDO.java @@ -32,6 +32,39 @@ public class ObjectStorageFileDO extends BaseEntity { @TableField("file_url") private String fileUrl; + @TableField("object_name") + private String objectName; + + @TableField("minio_url") + private String minioUrl; + + @TableField("oss_url") + private String ossUrl; + + @TableField("content_type") + private String contentType; + + @TableField("file_size") + private Long fileSize; + + @TableField("minio_upload_status") + private Integer minioUploadStatus; + + @TableField("oss_upload_status") + private Integer ossUploadStatus; + + @TableField("oss_retry_count") + private Integer ossRetryCount; + + @TableField("oss_last_error") + private String ossLastError; + + @TableField("oss_uploaded_at") + private LocalDateTime ossUploadedAt; + + @TableField("oss_last_retry_time") + private LocalDateTime ossLastRetryTime; + /** * 文件状态:1-可用,0-不可用,2-回收站 */ diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessageListener.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessageListener.java new file mode 100644 index 00000000..52f3ceae --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessageListener.java @@ -0,0 +1,29 @@ +package com.xiaowang.yuminailcore.modules.file.mq; + +import com.xiaowang.yuminailcore.config.RabbitMQConfig; +import com.xiaowang.yuminailcore.modules.file.dto.OssBackupUploadMessage; +import com.xiaowang.yuminailcore.modules.file.service.OssBackupService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.rabbit.annotation.RabbitListener; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class OssBackupMessageListener { + + private final OssBackupService ossBackupService; + + @RabbitListener(queues = RabbitMQConfig.FILE_OSS_BACKUP_QUEUE) + public void handle(OssBackupUploadMessage message) { + if (message == null || message.getFileId() == null) { + return; + } + try { + ossBackupService.backupFileToOss(message.getFileId()); + } catch (Exception e) { + log.warn("Handle OSS backup message failed, fileId={}", message.getFileId(), e); + } + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessagePublisher.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessagePublisher.java new file mode 100644 index 00000000..8870dcaf --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/mq/OssBackupMessagePublisher.java @@ -0,0 +1,31 @@ +package com.xiaowang.yuminailcore.modules.file.mq; + +import com.xiaowang.yuminailcore.config.RabbitMQConfig; +import com.xiaowang.yuminailcore.modules.file.dto.OssBackupUploadMessage; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.amqp.rabbit.core.RabbitTemplate; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class OssBackupMessagePublisher { + + private final RabbitTemplate rabbitTemplate; + + public void publish(Long fileId) { + if (fileId == null || fileId <= 0) { + return; + } + try { + rabbitTemplate.convertAndSend( + RabbitMQConfig.FILE_OSS_BACKUP_EXCHANGE, + RabbitMQConfig.FILE_OSS_BACKUP_ROUTING_KEY, + new OssBackupUploadMessage(fileId) + ); + } catch (Exception e) { + log.warn("Publish OSS backup message failed, fileId={}", fileId, e); + } + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/scheduler/OssBackupRetryScheduler.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/scheduler/OssBackupRetryScheduler.java new file mode 100644 index 00000000..3f00b372 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/scheduler/OssBackupRetryScheduler.java @@ -0,0 +1,44 @@ +package com.xiaowang.yuminailcore.modules.file.scheduler; + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.yuminailcore.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.yuminailcore.modules.file.mapper.ObjectStorageFileMapper; +import com.xiaowang.yuminailcore.modules.file.service.OssBackupService; +import com.xiaowang.yuminailcore.modules.file.service.impl.OssBackupServiceImpl; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.List; + +@Slf4j +@Component +@RequiredArgsConstructor +public class OssBackupRetryScheduler { + + private static final int BATCH_LIMIT = 500; + + private final ObjectStorageFileMapper objectStorageFileMapper; + private final OssBackupService ossBackupService; + + @Scheduled(cron = "0 0 2 * * ?", zone = "Asia/Shanghai") + public void retryPendingOrFailedBackups() { + List files = objectStorageFileMapper.selectList( + Wrappers.lambdaQuery(ObjectStorageFileDO.class) + .eq(ObjectStorageFileDO::getStatus, 1) + .eq(ObjectStorageFileDO::getMinioUploadStatus, OssBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED) + .in(ObjectStorageFileDO::getOssUploadStatus, + OssBackupServiceImpl.UPLOAD_STATUS_PENDING, + OssBackupServiceImpl.UPLOAD_STATUS_FAILED) + .last("LIMIT " + BATCH_LIMIT) + ); + for (ObjectStorageFileDO file : files) { + try { + ossBackupService.backupFileToOss(file.getId()); + } catch (Exception e) { + log.warn("Retry OSS backup failed, fileId={}", file.getId(), e); + } + } + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/AliyunOssService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/AliyunOssService.java new file mode 100644 index 00000000..95d5f235 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/AliyunOssService.java @@ -0,0 +1,10 @@ +package com.xiaowang.yuminailcore.modules.file.service; + +import java.io.InputStream; + +public interface AliyunOssService { + + String uploadStream(String objectName, InputStream inputStream, long fileSize, String contentType); + + String getPresignedUrl(String objectName); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/ObjectStorageFileService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/ObjectStorageFileService.java index eac5db61..9052778d 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/ObjectStorageFileService.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/ObjectStorageFileService.java @@ -73,4 +73,6 @@ public interface ObjectStorageFileService extends IService * @return 文件VO列表 */ List listObjectStorageFilesByStatus(Integer status); + + void evictObjectStorageFileCache(Long id); } diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/OssBackupService.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/OssBackupService.java new file mode 100644 index 00000000..00236015 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/OssBackupService.java @@ -0,0 +1,6 @@ +package com.xiaowang.yuminailcore.modules.file.service; + +public interface OssBackupService { + + void backupFileToOss(Long fileId); +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/AliyunOssServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/AliyunOssServiceImpl.java new file mode 100644 index 00000000..bc552687 --- /dev/null +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/AliyunOssServiceImpl.java @@ -0,0 +1,65 @@ +package com.xiaowang.yuminailcore.modules.file.service.impl; + +import com.aliyun.oss.HttpMethod; +import com.aliyun.oss.OSS; +import com.aliyun.oss.model.GeneratePresignedUrlRequest; +import com.aliyun.oss.model.ObjectMetadata; +import com.aliyun.oss.model.PutObjectRequest; +import com.xiaowang.yuminailcore.modules.file.config.AliyunOssConfig; +import com.xiaowang.yuminailcore.modules.file.service.AliyunOssService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.io.InputStream; +import java.net.URL; +import java.util.Date; + +@Slf4j +@Service +@RequiredArgsConstructor +public class AliyunOssServiceImpl implements AliyunOssService { + + private final ObjectProvider ossClientProvider; + private final AliyunOssConfig aliyunOssConfig; + + @Override + public String uploadStream(String objectName, InputStream inputStream, long fileSize, String contentType) { + OSS ossClient = requireClient(); + ObjectMetadata metadata = new ObjectMetadata(); + if (fileSize >= 0) { + metadata.setContentLength(fileSize); + } + if (StringUtils.hasText(contentType)) { + metadata.setContentType(contentType); + } + ossClient.putObject(new PutObjectRequest(aliyunOssConfig.getBucketName(), objectName, inputStream, metadata)); + log.info("Aliyun OSS backup uploaded: {}", objectName); + return "oss://" + aliyunOssConfig.getBucketName() + "/" + objectName; + } + + @Override + public String getPresignedUrl(String objectName) { + OSS ossClient = requireClient(); + Date expiration = new Date(System.currentTimeMillis() + + aliyunOssConfig.getSignedUrlExpireMinutes() * 60L * 1000L); + GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest( + aliyunOssConfig.getBucketName(), + objectName, + HttpMethod.GET + ); + request.setExpiration(expiration); + URL url = ossClient.generatePresignedUrl(request); + return url.toString(); + } + + private OSS requireClient() { + OSS ossClient = ossClientProvider.getIfAvailable(); + if (ossClient == null) { + throw new IllegalStateException("Aliyun OSS is not enabled or not configured"); + } + return ossClient; + } +} diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageFileServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageFileServiceImpl.java index a2231285..fb7a9801 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageFileServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageFileServiceImpl.java @@ -7,12 +7,14 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageFileDTO; import com.xiaowang.yuminailcore.modules.file.entity.ObjectStorageFileDO; import com.xiaowang.yuminailcore.modules.file.mapper.ObjectStorageFileMapper; +import com.xiaowang.yuminailcore.modules.file.mq.OssBackupMessagePublisher; import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService; import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; import java.time.Duration; import java.util.Collection; @@ -53,6 +55,7 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl 0; if (updated) { /** @@ -229,6 +225,17 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl= MINIO_HEALTH_CACHE_MILLIS; + } + + private void markMinioHealth(boolean healthy) { + minioHealthy = healthy; + minioHealthCheckedAt = System.currentTimeMillis(); + } + + private String firstText(String... values) { + if (values == null) { + return null; + } + for (String value : values) { + if (StringUtils.hasText(value)) { + return value; + } + } + return null; + } + private String extractObjectNameFromPath(String path) { String bucketPrefix = "/" + minioConfig.getBucketName() + "/"; if (path.startsWith(bucketPrefix)) { @@ -110,7 +198,7 @@ public class ObjectStorageUrlSupport { try { endpointPath = URI.create(minioConfig.getEndpoint()).getPath(); } catch (Exception e) { - log.warn("解析 MinIO endpoint 失败: {}", minioConfig.getEndpoint(), e); + log.warn("Parse MinIO endpoint failed: {}", minioConfig.getEndpoint(), e); } if (StringUtils.hasText(endpointPath) && !"/".equals(endpointPath)) { @@ -131,10 +219,48 @@ public class ObjectStorageUrlSupport { return ""; } - /** - * Purpose: trimBucketPrefix supports ObjectStorageUrlSupport.java by holding or executing the trim bucket prefix business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ + private String extractObjectNameFromUri(URI fileUri) { + String objectName = extractObjectNameFromPath(fileUri.getPath()); + if (StringUtils.hasText(objectName)) { + return objectName; + } + + try { + URI endpointUri = URI.create(minioConfig.getEndpoint()); + if (!sameAuthority(fileUri, endpointUri)) { + return ""; + } + return stripFirstPathSegment(fileUri.getPath()); + } catch (Exception e) { + log.warn("Parse MinIO endpoint failed: {}", minioConfig.getEndpoint(), e); + return ""; + } + } + + private boolean sameAuthority(URI left, URI right) { + return left.getScheme() != null + && left.getScheme().equalsIgnoreCase(right.getScheme()) + && left.getHost() != null + && left.getHost().equalsIgnoreCase(right.getHost()) + && normalizedPort(left) == normalizedPort(right); + } + + private int normalizedPort(URI uri) { + if (uri.getPort() >= 0) { + return uri.getPort(); + } + return "https".equalsIgnoreCase(uri.getScheme()) ? 443 : 80; + } + + private String stripFirstPathSegment(String path) { + String normalizedPath = stripLeadingSlash(path); + int slashIndex = normalizedPath.indexOf('/'); + if (slashIndex < 0 || slashIndex == normalizedPath.length() - 1) { + return ""; + } + return normalizedPath.substring(slashIndex + 1); + } + private String trimBucketPrefix(String rawValue) { String normalized = stripLeadingSlash(rawValue); String bucketPrefix = minioConfig.getBucketName() + "/"; @@ -144,10 +270,6 @@ public class ObjectStorageUrlSupport { return normalized; } - /** - * Purpose: stripLeadingSlash supports ObjectStorageUrlSupport.java by holding or executing the strip leading slash business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ private String stripLeadingSlash(String rawValue) { String normalized = rawValue; while (normalized.startsWith("/")) { @@ -156,10 +278,6 @@ public class ObjectStorageUrlSupport { return normalized; } - /** - * Purpose: stripQuery supports ObjectStorageUrlSupport.java by holding or executing the strip query business role. - * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. - */ private String stripQuery(String rawValue) { int queryIndex = rawValue.indexOf('?'); return queryIndex >= 0 ? rawValue.substring(0, queryIndex) : rawValue; diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/vo/ObjectStorageFileVO.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/vo/ObjectStorageFileVO.java index bc778bec..a159e6b4 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/vo/ObjectStorageFileVO.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/vo/ObjectStorageFileVO.java @@ -29,6 +29,28 @@ public class ObjectStorageFileVO { */ private String fileUrl; + private String objectName; + + private String minioUrl; + + private String ossUrl; + + private String contentType; + + private Long fileSize; + + private Integer minioUploadStatus; + + private Integer ossUploadStatus; + + private Integer ossRetryCount; + + private String ossLastError; + + private LocalDateTime ossUploadedAt; + + private LocalDateTime ossLastRetryTime; + /** * 文件上传时间 */ diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/message/service/impl/SystemMessageServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/message/service/impl/SystemMessageServiceImpl.java index 64f4ed5e..e1be4592 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/message/service/impl/SystemMessageServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/message/service/impl/SystemMessageServiceImpl.java @@ -692,7 +692,7 @@ public class SystemMessageServiceImpl extends ServiceImpl im * Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final ObjectStorageFileService objectStorageFileService; + private final ObjectStorageUrlSupport objectStorageUrlSupport; /** * Variable `couponMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -488,7 +490,7 @@ public class ProductServiceImpl extends ServiceImpl im for (Long fileId : parseDelimitedLongIds(productDO.getImageFileIds(), ",")) { ObjectStorageFileVO fileVO = context.files().get(fileId); if (fileVO != null && StringUtils.hasText(fileVO.getFileUrl())) { - imageUrls.add(fileVO.getFileUrl()); + imageUrls.add(objectStorageUrlSupport.toAccessibleUrl(fileVO)); } } productVO.setImageUrls(imageUrls); diff --git a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/shop/service/impl/ShopServiceImpl.java b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/shop/service/impl/ShopServiceImpl.java index 55dee7da..60734493 100644 --- a/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/shop/service/impl/ShopServiceImpl.java +++ b/YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/shop/service/impl/ShopServiceImpl.java @@ -694,7 +694,7 @@ public class ShopServiceImpl extends ServiceImpl implements for (Long fileId : fileIds) { ObjectStorageFileVO file = fileMap.get(fileId); if (file != null && StringUtils.hasText(file.getFileUrl())) { - urls.add(objectStorageUrlSupport.toAccessibleUrl(file.getFileUrl())); + urls.add(objectStorageUrlSupport.toAccessibleUrl(file)); } } return urls; diff --git a/YumiNail-Core/src/main/resources/files/YumiNail.sql b/YumiNail-Core/src/main/resources/files/YumiNail.sql index 6848cd54..7a632b43 100644 --- a/YumiNail-Core/src/main/resources/files/YumiNail.sql +++ b/YumiNail-Core/src/main/resources/files/YumiNail.sql @@ -276,6 +276,17 @@ create table t_object_storage_file primary key comment '对象存储文件主键索引', file_name varchar(100) not null comment '文件名称', file_url text not null comment '文件访问链接', + object_name varchar(512) null comment '对象存储Key', + minio_url text null comment 'MinIO访问链接', + oss_url text null comment '阿里云OSS内部备份链接', + content_type varchar(128) null comment '文件Content-Type', + file_size bigint unsigned null comment '文件大小,单位字节', + minio_upload_status tinyint unsigned default 0 not null comment 'MinIO上传状态:0-PENDING,1-SUCCEEDED,2-FAILED', + oss_upload_status tinyint unsigned default 0 not null comment 'OSS上传状态:0-PENDING,1-SUCCEEDED,2-FAILED', + oss_retry_count int unsigned default 0 not null comment 'OSS备份重试次数', + oss_last_error varchar(500) null comment '最近一次OSS备份失败原因', + oss_uploaded_at datetime null comment 'OSS备份成功时间', + oss_last_retry_time datetime null comment '最近一次OSS备份重试时间', create_time datetime default CURRENT_TIMESTAMP not null comment '文件上传时间', update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '文件更新时间', status tinyint unsigned default 1 null comment '文件状态:1-可用,0-不可用,2-回收站', @@ -288,6 +299,10 @@ create index idx_status on t_object_storage_file (status) comment '按文件状态查询的索引'; +create index idx_object_storage_file_oss_retry + on t_object_storage_file (oss_upload_status, minio_upload_status, status) + comment 'OSS备份失败重试扫描索引'; + -- auto-generated definition create table t_order ( @@ -924,6 +939,25 @@ CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal( CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间'''); CALL sp_add_column_if_not_exists('t_balance', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'object_name', 'varchar(512) NULL COMMENT ''对象存储Key'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'minio_url', 'text NULL COMMENT ''MinIO访问链接'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_url', 'text NULL COMMENT ''阿里云OSS内部备份链接'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'content_type', 'varchar(128) NULL COMMENT ''文件Content-Type'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'file_size', 'bigint unsigned NULL COMMENT ''文件大小,单位字节'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'minio_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''MinIO上传状态:0-PENDING,1-SUCCEEDED,2-FAILED'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''OSS上传状态:0-PENDING,1-SUCCEEDED,2-FAILED'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_retry_count', 'int unsigned NOT NULL DEFAULT 0 COMMENT ''OSS备份重试次数'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_last_error', 'varchar(500) NULL COMMENT ''最近一次OSS备份失败原因'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_uploaded_at', 'datetime NULL COMMENT ''OSS备份成功时间'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_last_retry_time', 'datetime NULL COMMENT ''最近一次OSS备份重试时间'''); +UPDATE t_object_storage_file +SET minio_url = COALESCE(minio_url, file_url), + minio_upload_status = CASE WHEN minio_upload_status IS NULL OR minio_upload_status = 0 THEN 1 ELSE minio_upload_status END, + oss_upload_status = COALESCE(oss_upload_status, 0), + oss_retry_count = COALESCE(oss_retry_count, 0) +WHERE status = 1; +CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_oss_retry', '(`oss_upload_status`, `minio_upload_status`, `status`)'); + UPDATE t_balance SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00) WHERE total_recharge_amount IS NULL; diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/artist/service/impl/NailArtistInfoServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/artist/service/impl/NailArtistInfoServiceImplTest.java index d995a760..9bd2d32f 100644 --- a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/artist/service/impl/NailArtistInfoServiceImplTest.java +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/artist/service/impl/NailArtistInfoServiceImplTest.java @@ -18,6 +18,7 @@ import com.xiaowang.yuminailcore.modules.product.mapper.ProductMapper; import com.xiaowang.yuminailcore.modules.shop.mapper.ShopMapper; import com.xiaowang.yuminailcore.modules.user.mapper.UserMapper; import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService; +import com.xiaowang.yuminailcore.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.yuminailcore.modules.shop.support.UserShopBindingSupport; import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistAvailabilityVO; import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistProfileVO; @@ -63,6 +64,8 @@ class NailArtistInfoServiceImplTest { @Mock private ObjectStorageFileService objectStorageFileService; @Mock + private ObjectStorageUrlSupport objectStorageUrlSupport; + @Mock private ArtistScheduleMapper artistScheduleMapper; @Mock private AppointmentReservationMapper appointmentReservationMapper; @@ -82,9 +85,12 @@ class NailArtistInfoServiceImplTest { ReflectionTestUtils.setField(service, "orderItemMapper", orderItemMapper); ReflectionTestUtils.setField(service, "orderArtistReviewMapper", orderArtistReviewMapper); ReflectionTestUtils.setField(service, "objectStorageFileService", objectStorageFileService); + ReflectionTestUtils.setField(service, "objectStorageUrlSupport", objectStorageUrlSupport); ReflectionTestUtils.setField(service, "artistScheduleMapper", artistScheduleMapper); ReflectionTestUtils.setField(service, "appointmentReservationMapper", appointmentReservationMapper); when(userShopBindingSupport.listShopOptionsByUserId(any(), anyBoolean(), anyBoolean())).thenReturn(List.of()); + when(objectStorageUrlSupport.toAccessibleUrl(any(ObjectStorageFileVO.class))) + .thenAnswer(invocation -> invocation.getArgument(0, ObjectStorageFileVO.class).getFileUrl()); } @Test diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/FileOssBackupConfigurationTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/FileOssBackupConfigurationTest.java new file mode 100644 index 00000000..cfff92b2 --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/FileOssBackupConfigurationTest.java @@ -0,0 +1,25 @@ +package com.xiaowang.yuminailcore.modules.file; + +import com.xiaowang.yuminailcore.config.RabbitMQConfig; +import com.xiaowang.yuminailcore.modules.file.config.AliyunOssConfig; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class FileOssBackupConfigurationTest { + + @Test + void rabbitMqConfigExposesDurableOssBackupRouteConstants() { + assertThat(RabbitMQConfig.FILE_OSS_BACKUP_EXCHANGE).isEqualTo("yuminail.file.oss.backup.exchange"); + assertThat(RabbitMQConfig.FILE_OSS_BACKUP_QUEUE).isEqualTo("yuminail.file.oss.backup.queue"); + assertThat(RabbitMQConfig.FILE_OSS_BACKUP_ROUTING_KEY).isEqualTo("yuminail.file.oss.backup"); + } + + @Test + void aliyunOssConfigUsesPrivateBucketDefaults() { + AliyunOssConfig config = new AliyunOssConfig(); + + assertThat(config.getBucketName()).isEqualTo("fingertipdesigner"); + assertThat(config.getSignedUrlExpireMinutes()).isEqualTo(30); + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/controller/front/FrontendFileControllerTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/controller/front/FrontendFileControllerTest.java index 4340243e..2b825898 100644 --- a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/controller/front/FrontendFileControllerTest.java +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/controller/front/FrontendFileControllerTest.java @@ -1,17 +1,18 @@ package com.xiaowang.yuminailcore.modules.file.controller.front; import com.xiaowang.yuminailcore.common.Result; -import com.xiaowang.yuminailcore.modules.product.mapper.EffectDiagramMapper; -import com.xiaowang.yuminailcore.modules.product.mapper.ProductMapper; -import com.xiaowang.yuminailcore.modules.shop.mapper.ShopMapper; -import com.xiaowang.yuminailcore.modules.file.service.MinioService; import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService; import com.xiaowang.yuminailcore.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.yuminailcore.modules.product.mapper.EffectDiagramMapper; +import com.xiaowang.yuminailcore.modules.product.mapper.ProductMapper; +import com.xiaowang.yuminailcore.modules.shop.mapper.ShopMapper; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -20,7 +21,7 @@ import static org.mockito.Mockito.when; class FrontendFileControllerTest { private ObjectStorageFileService objectStorageFileService; - private MinioService minioService; + private ObjectStorageUrlSupport objectStorageUrlSupport; private ProductMapper productMapper; private ShopMapper shopMapper; private EffectDiagramMapper effectDiagramMapper; @@ -29,20 +30,17 @@ class FrontendFileControllerTest { @BeforeEach void setUp() { objectStorageFileService = mock(ObjectStorageFileService.class); - minioService = mock(MinioService.class); - ObjectStorageUrlSupport objectStorageUrlSupport = mock(ObjectStorageUrlSupport.class); + objectStorageUrlSupport = mock(ObjectStorageUrlSupport.class); productMapper = mock(ProductMapper.class); shopMapper = mock(ShopMapper.class); effectDiagramMapper = mock(EffectDiagramMapper.class); controller = new FrontendFileController( objectStorageFileService, - minioService, objectStorageUrlSupport, productMapper, shopMapper, effectDiagramMapper ); - when(objectStorageUrlSupport.extractObjectName("https://cdn.test/public/a.png")).thenReturn("public/a.png"); } @Test @@ -56,16 +54,17 @@ class FrontendFileControllerTest { Result result = controller.getSignedUrl(12L, 60); assertThat(result.getCode()).isNotEqualTo(200); - assertThat(result.getMessage()).contains("文件不可公开访问"); - verify(minioService, never()).getPresignedUrl(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyInt()); + verify(objectStorageUrlSupport, never()).toAccessibleUrl(any(ObjectStorageFileVO.class), anyInt()); + verify(objectStorageUrlSupport, never()).getSignedUrlOrThrow(any(ObjectStorageFileVO.class), anyInt()); } @Test void getSignedUrlAllowsPublicProductImageReference() throws Exception { ObjectStorageFileVO file = file(); + file.setObjectName("public/a.png"); when(objectStorageFileService.getObjectStorageFileById(12L)).thenReturn(file); when(productMapper.countPublicImageReference(12L)).thenReturn(1L); - when(minioService.getPresignedUrl("public/a.png", 30)).thenReturn("https://signed.test/public/a.png"); + when(objectStorageUrlSupport.getSignedUrlOrThrow(file, 30)).thenReturn("https://signed.test/public/a.png"); Result result = controller.getSignedUrl(12L, 30); @@ -84,7 +83,7 @@ class FrontendFileControllerTest { assertThat(result.getCode()).isEqualTo(200); assertThat(result.getData()).isEqualTo("https://acceptance.local/images/public-a.png"); - verify(minioService, never()).getPresignedUrl(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.anyInt()); + verify(objectStorageUrlSupport, never()).getSignedUrlOrThrow(any(ObjectStorageFileVO.class), anyInt()); } private ObjectStorageFileVO file() { diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/scheduler/OssBackupRetrySchedulerTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/scheduler/OssBackupRetrySchedulerTest.java new file mode 100644 index 00000000..aa56f58c --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/scheduler/OssBackupRetrySchedulerTest.java @@ -0,0 +1,49 @@ +package com.xiaowang.yuminailcore.modules.file.scheduler; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.xiaowang.yuminailcore.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.yuminailcore.modules.file.mapper.ObjectStorageFileMapper; +import com.xiaowang.yuminailcore.modules.file.service.OssBackupService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class OssBackupRetrySchedulerTest { + + private ObjectStorageFileMapper objectStorageFileMapper; + private OssBackupService ossBackupService; + private OssBackupRetryScheduler scheduler; + + @BeforeEach + void setUp() { + objectStorageFileMapper = mock(ObjectStorageFileMapper.class); + ossBackupService = mock(OssBackupService.class); + scheduler = new OssBackupRetryScheduler(objectStorageFileMapper, ossBackupService); + } + + @Test + void retryPendingOrFailedBackupsScansRetryableFilesAndDispatchesBackup() { + ObjectStorageFileDO pending = new ObjectStorageFileDO(); + pending.setId(1L); + ObjectStorageFileDO failed = new ObjectStorageFileDO(); + failed.setId(2L); + when(objectStorageFileMapper.selectList(any())).thenReturn(List.of(pending, failed)); + + scheduler.retryPendingOrFailedBackups(); + + @SuppressWarnings("unchecked") + ArgumentCaptor> captor = ArgumentCaptor.forClass(Wrapper.class); + verify(objectStorageFileMapper).selectList(captor.capture()); + assertThat(captor.getValue()).isNotNull(); + verify(ossBackupService).backupFileToOss(1L); + verify(ossBackupService).backupFileToOss(2L); + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageFileServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageFileServiceImplTest.java new file mode 100644 index 00000000..534841a8 --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/service/impl/ObjectStorageFileServiceImplTest.java @@ -0,0 +1,69 @@ +package com.xiaowang.yuminailcore.modules.file.service.impl; + +import com.xiaowang.yuminailcore.config.AppCacheProperties; +import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageFileDTO; +import com.xiaowang.yuminailcore.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.yuminailcore.modules.file.mapper.ObjectStorageFileMapper; +import com.xiaowang.yuminailcore.modules.file.mq.OssBackupMessagePublisher; +import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ObjectStorageFileServiceImplTest { + + private ObjectStorageFileMapper objectStorageFileMapper; + private OssBackupMessagePublisher ossBackupMessagePublisher; + private ObjectStorageFileServiceImpl service; + + @BeforeEach + void setUp() { + objectStorageFileMapper = mock(ObjectStorageFileMapper.class); + MultiLevelCacheService multiLevelCacheService = mock(MultiLevelCacheService.class); + AppCacheProperties appCacheProperties = new AppCacheProperties(); + ossBackupMessagePublisher = mock(OssBackupMessagePublisher.class); + service = new ObjectStorageFileServiceImpl( + objectStorageFileMapper, + multiLevelCacheService, + appCacheProperties, + ossBackupMessagePublisher + ); + } + + @Test + void createObjectStorageFilePublishesOssBackupMessageAfterMinioUploadSucceeded() { + when(objectStorageFileMapper.insert(any(ObjectStorageFileDO.class))).thenAnswer(invocation -> { + ObjectStorageFileDO file = invocation.getArgument(0); + file.setId(66L); + return 1; + }); + + ObjectStorageFileDTO dto = new ObjectStorageFileDTO(); + dto.setFileName("a.png"); + dto.setFileUrl("http://127.0.0.1:9000/yuminail/product/a.png"); + dto.setObjectName("product/a.png"); + dto.setMinioUrl(dto.getFileUrl()); + dto.setContentType("image/png"); + dto.setFileSize(3L); + dto.setStatus(1); + dto.setMinioUploadStatus(1); + dto.setOssUploadStatus(0); + dto.setOssRetryCount(0); + + Long fileId = service.createObjectStorageFile(dto); + + assertThat(fileId).isEqualTo(66L); + ArgumentCaptor captor = ArgumentCaptor.forClass(ObjectStorageFileDO.class); + verify(objectStorageFileMapper).insert(captor.capture()); + assertThat(captor.getValue().getObjectName()).isEqualTo("product/a.png"); + assertThat(captor.getValue().getMinioUploadStatus()).isEqualTo(1); + assertThat(captor.getValue().getOssUploadStatus()).isEqualTo(0); + verify(ossBackupMessagePublisher).publish(66L); + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/service/impl/OssBackupServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/service/impl/OssBackupServiceImplTest.java new file mode 100644 index 00000000..e77e3100 --- /dev/null +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/service/impl/OssBackupServiceImplTest.java @@ -0,0 +1,93 @@ +package com.xiaowang.yuminailcore.modules.file.service.impl; + +import com.xiaowang.yuminailcore.modules.file.entity.ObjectStorageFileDO; +import com.xiaowang.yuminailcore.modules.file.mapper.ObjectStorageFileMapper; +import com.xiaowang.yuminailcore.modules.file.service.AliyunOssService; +import com.xiaowang.yuminailcore.modules.file.service.MinioService; +import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import java.io.ByteArrayInputStream; +import java.nio.charset.StandardCharsets; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class OssBackupServiceImplTest { + + private ObjectStorageFileMapper objectStorageFileMapper; + private MinioService minioService; + private AliyunOssService aliyunOssService; + private ObjectStorageFileService objectStorageFileService; + private OssBackupServiceImpl service; + + @BeforeEach + void setUp() { + objectStorageFileMapper = mock(ObjectStorageFileMapper.class); + minioService = mock(MinioService.class); + aliyunOssService = mock(AliyunOssService.class); + objectStorageFileService = mock(ObjectStorageFileService.class); + service = new OssBackupServiceImpl(objectStorageFileMapper, minioService, aliyunOssService, objectStorageFileService); + } + + @Test + void backupFileToOssMarksFileSucceededAfterUploadingMinioStreamToOss() throws Exception { + ObjectStorageFileDO file = activeMinioFile(); + byte[] bytes = "abc".getBytes(StandardCharsets.UTF_8); + when(objectStorageFileMapper.selectById(88L)).thenReturn(file); + when(minioService.downloadFile("product/a.png")).thenReturn(new ByteArrayInputStream(bytes)); + when(aliyunOssService.uploadStream(eq("product/a.png"), any(), eq(3L), eq("image/png"))) + .thenReturn("oss://fingertipdesigner/product/a.png"); + + service.backupFileToOss(88L); + + ArgumentCaptor captor = ArgumentCaptor.forClass(ObjectStorageFileDO.class); + verify(objectStorageFileMapper).updateById(captor.capture()); + ObjectStorageFileDO updated = captor.getValue(); + assertThat(updated.getId()).isEqualTo(88L); + assertThat(updated.getOssUrl()).isEqualTo("oss://fingertipdesigner/product/a.png"); + assertThat(updated.getOssUploadStatus()).isEqualTo(1); + assertThat(updated.getOssUploadedAt()).isNotNull(); + assertThat(updated.getOssLastError()).isNull(); + verify(objectStorageFileService).evictObjectStorageFileCache(88L); + } + + @Test + void backupFileToOssMarksFileFailedAndTruncatesErrorWhenOssUploadFails() throws Exception { + ObjectStorageFileDO file = activeMinioFile(); + file.setOssRetryCount(2); + when(objectStorageFileMapper.selectById(88L)).thenReturn(file); + when(minioService.downloadFile("product/a.png")).thenReturn(new ByteArrayInputStream(new byte[]{1})); + when(aliyunOssService.uploadStream(eq("product/a.png"), any(), eq(3L), eq("image/png"))) + .thenThrow(new IllegalStateException("x".repeat(700))); + + service.backupFileToOss(88L); + + ArgumentCaptor captor = ArgumentCaptor.forClass(ObjectStorageFileDO.class); + verify(objectStorageFileMapper).updateById(captor.capture()); + ObjectStorageFileDO updated = captor.getValue(); + assertThat(updated.getOssUploadStatus()).isEqualTo(2); + assertThat(updated.getOssRetryCount()).isEqualTo(3); + assertThat(updated.getOssLastRetryTime()).isNotNull(); + assertThat(updated.getOssLastError()).hasSizeLessThanOrEqualTo(500); + verify(objectStorageFileService).evictObjectStorageFileCache(88L); + } + + private ObjectStorageFileDO activeMinioFile() { + ObjectStorageFileDO file = new ObjectStorageFileDO(); + file.setId(88L); + file.setStatus(1); + file.setObjectName("product/a.png"); + file.setMinioUploadStatus(1); + file.setOssUploadStatus(0); + file.setContentType("image/png"); + file.setFileSize(3L); + return file; + } +} diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/support/ObjectStorageUrlSupportTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/support/ObjectStorageUrlSupportTest.java index da453875..fd34cbf2 100644 --- a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/support/ObjectStorageUrlSupportTest.java +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/support/ObjectStorageUrlSupportTest.java @@ -1,41 +1,107 @@ package com.xiaowang.yuminailcore.modules.file.support; import com.xiaowang.yuminailcore.config.MinioConfig; +import com.xiaowang.yuminailcore.modules.file.service.AliyunOssService; import com.xiaowang.yuminailcore.modules.file.service.MinioService; +import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; -import com.xiaowang.yuminailcore.common.Result; class ObjectStorageUrlSupportTest { private MinioService minioService; + private AliyunOssService aliyunOssService; private ObjectStorageUrlSupport support; @BeforeEach void setUp() { minioService = mock(MinioService.class); + aliyunOssService = mock(AliyunOssService.class); + MinioConfig config = new MinioConfig(); config.setEndpoint("http://127.0.0.1:9000"); config.setBucketName("yuminail"); - support = new ObjectStorageUrlSupport(minioService, config); + + support = new ObjectStorageUrlSupport(minioService, config, aliyunOssService); } @Test void toAccessibleUrlFallsBackToOriginalExternalUrlWhenObjectNameCannotBeExtracted() { - String externalUrl = "https://acceptance.local/assets/作品图.jpg"; + String externalUrl = "https://acceptance.local/assets/product-a.jpg"; String result = support.toAccessibleUrl(externalUrl); assertThat(result).isEqualTo(externalUrl); - verifyNoInteractions(minioService); + verifyNoInteractions(minioService, aliyunOssService); } @Test void extractObjectNameStillAcceptsRawObjectName() { - assertThat(support.extractObjectName("product/作品图.jpg?x=1")).isEqualTo("product/作品图.jpg"); + assertThat(support.extractObjectName("product/a.jpg?x=1")).isEqualTo("product/a.jpg"); + } + + @Test + void toAccessibleUrlReturnsNullInsteadOfRawUrlWhenStringObjectSigningFails() throws Exception { + when(minioService.getPresignedUrl("product/a.jpg", 60)).thenThrow(new IllegalStateException("minio down")); + + String result = support.toAccessibleUrl("http://127.0.0.1:9000/yuminail/product/a.jpg"); + + assertThat(result).isNull(); + } + + @Test + void toAccessibleUrlFallsBackToOssSignedUrlWhenMinioSigningFailsAndBackupSucceeded() throws Exception { + ObjectStorageFileVO file = new ObjectStorageFileVO(); + file.setId(12L); + file.setFileUrl("http://127.0.0.1:9000/yuminail/product/a.png"); + file.setMinioUrl("http://127.0.0.1:9000/yuminail/product/a.png"); + file.setObjectName("product/a.png"); + file.setOssUploadStatus(1); + + when(minioService.getPresignedUrl("product/a.png", 60)).thenThrow(new IllegalStateException("minio down")); + when(aliyunOssService.getPresignedUrl("product/a.png")).thenReturn("https://oss-signed.test/product/a.png"); + + String result = support.toAccessibleUrl(file); + + assertThat(result).isEqualTo("https://oss-signed.test/product/a.png"); + } + + @Test + void toAccessibleUrlReturnsNullInsteadOfRawObjectStorageUrlWhenBothBackendsAreUnavailable() throws Exception { + ObjectStorageFileVO file = new ObjectStorageFileVO(); + file.setId(12L); + file.setFileUrl("http://127.0.0.1:9000/yuminail/product/a.png"); + file.setMinioUrl("http://127.0.0.1:9000/yuminail/product/a.png"); + file.setObjectName("product/a.png"); + file.setOssUploadStatus(1); + + when(minioService.getPresignedUrl("product/a.png", 60)).thenThrow(new IllegalStateException("minio down")); + when(aliyunOssService.getPresignedUrl("product/a.png")).thenThrow(new IllegalStateException("oss down")); + + String result = support.toAccessibleUrl(file); + + assertThat(result).isNull(); + } + + @Test + void getSignedUrlOrThrowReportsClearFailureWhenBothBackendsAreUnavailable() throws Exception { + ObjectStorageFileVO file = new ObjectStorageFileVO(); + file.setId(12L); + file.setFileUrl("http://127.0.0.1:9000/yuminail/product/a.png"); + file.setObjectName("product/a.png"); + file.setOssUploadStatus(1); + + when(minioService.getPresignedUrl("product/a.png", 20)).thenThrow(new IllegalStateException("minio down")); + when(aliyunOssService.getPresignedUrl("product/a.png")).thenThrow(new IllegalStateException("oss down")); + + assertThatThrownBy(() -> support.getSignedUrlOrThrow(file, 20)) + .isInstanceOf(IllegalStateException.class) + .hasMessageContaining("No available object storage signed URL"); } } diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/product/service/impl/ProductServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/product/service/impl/ProductServiceImplTest.java index ef3f4bd3..77e7355e 100644 --- a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/product/service/impl/ProductServiceImplTest.java +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/product/service/impl/ProductServiceImplTest.java @@ -8,6 +8,7 @@ import com.xiaowang.yuminailcore.modules.product.mapper.ProductMapper; import com.xiaowang.yuminailcore.modules.shop.mapper.ShopMapper; import com.xiaowang.yuminailcore.modules.product.mapper.TagMapper; import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService; +import com.xiaowang.yuminailcore.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.yuminailcore.modules.artist.support.BookableArtistSupport; import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService; import com.xiaowang.yuminailcore.modules.product.vo.ProductVO; @@ -36,6 +37,9 @@ class ProductServiceImplTest { @Mock private ObjectStorageFileService objectStorageFileService; + @Mock + private ObjectStorageUrlSupport objectStorageUrlSupport; + @Mock private CouponMapper couponMapper; @@ -59,6 +63,7 @@ class ProductServiceImplTest { productService = new ProductServiceImpl( productMapper, objectStorageFileService, + objectStorageUrlSupport, couponMapper, shopMapper, tagMapper, diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/shop/service/impl/ShopServiceImplTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/shop/service/impl/ShopServiceImplTest.java index b47b5b15..07618c95 100644 --- a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/shop/service/impl/ShopServiceImplTest.java +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/shop/service/impl/ShopServiceImplTest.java @@ -96,6 +96,8 @@ class ShopServiceImplTest { ); when(objectStorageUrlSupport.toAccessibleUrl(anyString())) .thenAnswer(invocation -> invocation.getArgument(0, String.class)); + when(objectStorageUrlSupport.toAccessibleUrl(any(ObjectStorageFileVO.class))) + .thenAnswer(invocation -> invocation.getArgument(0, ObjectStorageFileVO.class).getFileUrl()); } @Test diff --git a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/YumiNailSqlSchemaTest.java b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/YumiNailSqlSchemaTest.java index a9b49cd4..f3e17a93 100644 --- a/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/YumiNailSqlSchemaTest.java +++ b/YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/support/YumiNailSqlSchemaTest.java @@ -101,4 +101,29 @@ class YumiNailSqlSchemaTest { assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_user', 'contact_phone'"); assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_user', 'wechat_qr_code'"); } + + @Test + void objectStorageFileOssBackupColumnsAreSeeded() throws Exception { + String sql = Files.readString(Path.of("src/main/resources/files/YumiNail.sql")); + String initSql = Files.readString(Path.of("../scripts/sql/init/YumiNail.sql")); + + assertThat(sql).contains("object_name"); + assertThat(sql).contains("minio_url"); + assertThat(sql).contains("oss_url"); + assertThat(sql).contains("content_type"); + assertThat(sql).contains("file_size"); + assertThat(sql).contains("minio_upload_status"); + assertThat(sql).contains("oss_upload_status"); + assertThat(sql).contains("oss_retry_count"); + assertThat(sql).contains("oss_last_error"); + assertThat(sql).contains("oss_uploaded_at"); + assertThat(sql).contains("oss_last_retry_time"); + assertThat(sql).contains("CALL sp_add_column_if_not_exists('t_object_storage_file', 'object_name'"); + assertThat(sql).contains("CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_oss_retry'"); + assertThat(initSql).contains("object_name"); + assertThat(initSql).contains("minio_upload_status"); + assertThat(initSql).contains("oss_upload_status"); + assertThat(initSql).contains("CALL sp_add_column_if_not_exists('t_object_storage_file', 'object_name'"); + assertThat(initSql).contains("CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_oss_retry'"); + } } diff --git a/artifacts/real-upload-signed-preview.png b/artifacts/real-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eCb)nXo-jKQVm=2= zW6+Mnq^M!3#u!DuKeSLv!KZ#FjWfd8zg>$UWh4>QdUq#zuZ%}p9I2_B zyg`。 + +## 模块定位 + +| 模块 | 任务来了去哪 | +| --- | --- | +| `order` | 订单、订单项、购物车、报价、售后、改派、评价任务、订单状态机 | +| `planning` | 指尖管理师规划聚合、预约占用、排班容量、店长手动预约 | +| `file` | 文件上传、分片上传、MinIO、OSS 备份、签名 URL、图片回退 | +| `artist` | 美甲师资料、可预约能力、排班设置、请假、店长参与制作 | +| `shop` | 店铺资料、授权有效期、店铺绑定、店铺主题、联系方式 | +| `product` | 作品、标签、效果图、作品公开展示、作品可预约美甲师 | +| `auth` | 前台/后台登录、验证码、注册、Token 刷新、微信身份 | +| `security` | 权限、角色、安全审计、后台作用域、权限策略 | +| `message` | 系统消息、公告、用户消息状态、业务跳转消息 | +| `marketing` | 优惠券、活动、收藏、点赞、VIP 档位、成长体系 | +| `payment` | 支付单、退款单、余额、余额明细 | +| `content` | 评论、评价内容管理 | +| `inventory` | 耗材库存、库存记录、库存调整 | +| `integration` | MessageHub、微信小程序接口、Outbox、地图服务 | +| `analytics` | 后台工作台、经营看板、统计概览 | +| `system` | 健康检查、系统参数、法律协议、默认密码支撑 | +| `user` | 用户资料、用户资产、用户关系、邀请、协议确认 | + +## 局部结构 + +模块内优先使用: + +```text +controller/admin +controller/front +dto +entity +mapper +service +service/impl +support +vo +``` + +公共基础设施仍在根包: + +- `config` +- `annotation` +- `aspect` +- `filter` +- `utils` +- `support.cache` +- `support.id` +- `support.security` +- `common` + +## Mapper 扫描 + +Mapper 扫描位于: + +```text +YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/MyBatisPlusConfig.java +``` + +新增模块或 mapper 包时,确认 `@MapperScan` 覆盖。 + +## 当前高频链路 + +文件存储/OSS: + +- `modules/file/config/AliyunOssConfig.java` +- `modules/file/service/impl/ObjectStorageFileServiceImpl.java` +- `modules/file/service/impl/OssBackupServiceImpl.java` +- `modules/file/support/ObjectStorageUrlSupport.java` +- `modules/file/mq` +- `modules/file/scheduler` +- `config/RabbitMQConfig.java` + +规划排班: + +- `modules/planning` +- 关联 `modules/order`、`modules/artist`、`modules/shop` + +订单状态: + +- `modules/order` +- 重点查 `OrderStatus`、`OrderStateMachine`、订单服务实现和预约占用更新。 + +权限: + +- `modules/security` +- 根包 `support.security` +- 修改前确认当前店铺作用域和平台管理员规则。 + diff --git a/docx/handoff/CURRENT-STATE.md b/docx/handoff/CURRENT-STATE.md new file mode 100644 index 00000000..627a5247 --- /dev/null +++ b/docx/handoff/CURRENT-STATE.md @@ -0,0 +1,68 @@ +# Current State + +更新时间:2026-06-05 + +用途:记录当前真实状态。继续当前任务或做运维/联调前读本文件。 + +## 1. 工作区状态 + +当前 `git status --short` 显示大量未提交改动,不要默认回滚。 + +主要改动主题:MinIO 主存储 + 阿里云 OSS 异步备份与回退。 + +重点文件范围: + +- `YumiNail-Core/pom.xml`:新增/调整 OSS SDK 相关依赖。 +- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config/RabbitMQConfig.java`:新增 OSS 备份 exchange/queue/binding。 +- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules/file/**`:OSS 配置、服务、MQ、定时重试、签名 URL 回退、DTO/VO/DO 字段扩展。 +- `YumiNail-Core/src/main/resources/files/YumiNail.sql` 和 `scripts/sql/init/YumiNail.sql`:文件表新增 OSS/MinIO 状态字段。 +- `YumiNail-Core/src/test/java/com/xiaowang/yuminailcore/modules/file/**`:OSS 备份、重试、URL 回退相关测试。 +- `artifacts/real-upload-signed-preview.png`:真实上传签名预览产物。 + +其他已修改文件还涉及 artist、content、message、product、shop 读取文件 URL 的链路,属于文件访问回退改造影响面。 + +## 2. OSS/文件存储状态 + +- MinIO 仍是主上传链路。MinIO 上传失败时上传整体失败。 +- MinIO 上传成功后落库,再通过 RabbitMQ 异步备份到 OSS。 +- OSS bucket 产品名为 `FingertipDesigner`,实际合法 bucket 使用小写 `fingertipdesigner`。 +- OSS 私有桶访问必须用 30 分钟签名 URL。 +- 当前 Nacos 中 `aliyun.oss.enabled=false`,因为没有阿里云 endpoint、region、AK、SK。 +- 已做真实 MinIO 上传与签名预览测试;OSS MQ 备份触发过,但因 OSS 未配置失败。 + +## 3. Nacos 和生产服务状态 + +2026-06-05 已做过一次配置修复: + +- `YumiNail` 命名空间补齐 `yuminail-gateway.yaml`。 +- 补齐 `rabbitmq.yaml`,兼容 Gateway;保留 `rabbit-mq.yaml`,兼容 Core。 +- 补齐无后缀 `yuminail-core`,避免 Core 启动空配置警告。 +- `mybatis-plus.yaml` 修正旧包名,去掉 `com.xiaowang.messagehub.entity`。 +- `yuminail-core.yaml` 删除 `spring: null`,补 `aliyun.oss` 配置骨架。 +- Druid 监控访问范围已收紧。 + +生产服务当前状态: + +- `yumi-nail-core`:3 个健康实例,均 80 端口。 +- `yuminail-gateway`:3 个健康实例,均 80 端口。 +- Gateway 到 Core 基础路由已测:`/api/shop/list/simple`、`/api/legal-agreement/current` 返回 200。 + +## 4. 数据库状态 + +当前 Nacos `datasource.yaml` 临时指向 `mysql02:3306`。 + +原因: + +- `mysql-writer:3308`:TCP 通,但 JDBC 握手失败。 +- `mysql-writer:3306`、`mysql-writer:3307`、`mysql01:3306`、`mysql03:3306`:可连但 `read_only=1`、`super_read_only=1`。 +- `mysql02:3306`:当前验证为可写,`read_only=0`、`super_read_only=0`。 + +注意:直连 `mysql02:3306` 是恢复服务的临时方案。长期应修复 `mysql-writer:3308` HA writer 入口,然后切回 writer。 + +## 5. 已知未完成项 + +- 配置阿里云 OSS endpoint、region、AK、SK,并设置 `aliyun.oss.enabled=true`。 +- 重新做真实 OSS 备份成功、签名预览、MinIO 故障回退测试。 +- 修复 `mysql-writer:3308` HA writer 入口并切回 datasource。 +- 当前 OSS 备份代码和 SQL 仍需完整测试、GitNexus detect_changes、提交/推送。 + diff --git a/docx/handoff/HANDOFF-BOOT.md b/docx/handoff/HANDOFF-BOOT.md new file mode 100644 index 00000000..3c7683e2 --- /dev/null +++ b/docx/handoff/HANDOFF-BOOT.md @@ -0,0 +1,99 @@ +# YumiNail Handoff Boot + +更新时间:2026-06-05 + +用途:新会话只需先读 `AGENTS.md` 和本文件,即可建立最小项目上下文。不要把旧的 `docx/README.md`、`docx/MEMORY.md` 当首读资料,它们有乱码且信息过长。 + +## 1. 项目一句话 + +`E:\code\xiaowang` 是 YumiNail 美甲业务系统主仓库,包含 Web 前后台、用户微信小程序、指尖管理师小程序、Spring Cloud Gateway、Spring Boot Core、SQL 初始化和项目文档。 + +主链路: + +```text +Web / WeChatProgram / FingertipManager-Program + -> YumiNail-Gateway + -> YumiNail-Core + -> MySQL / Redis / MinIO / RabbitMQ / Nacos +``` + +## 2. 子系统地图 + +| 目录 | 职责 | 任务命中时读 | +| --- | --- | --- | +| `YumiNail-Core` | 核心业务后端,已按 `modules.` 业务分包 | `CORE-MODULES.md` | +| `YumiNail-Gateway` | 统一 API 入口、路由、白名单、Token 初筛 | `PROJECT-MAP.md` | +| `YumiNail-Frontend` | Vue 3 Web 用户端和后台管理端 | `PROJECT-MAP.md` | +| `WeChatProgram` | 普通用户微信小程序 | `PROJECT-MAP.md` | +| `FingertipManager-Program` | 指尖管理师店长排班小程序 | `PROJECT-MAP.md` | +| `scripts/sql` | 初始化 SQL 镜像目录 | `RISK-REGISTER.md` | +| `docx` | 文档、测试案例、交接资料 | 本目录 | + +## 3. 最高优先级规则 + +- 修改函数、类、方法前,先按 `AGENTS.md` 做 GitNexus upstream impact;提交前做 GitNexus detect_changes。 +- 不要回滚未提交改动。当前工作区有大量 OSS 备份相关改动,先读 `CURRENT-STATE.md`。 +- 手动编辑文件优先用 `apply_patch`。 +- 搜索优先 `rg` / `rg --files`。 +- 后端 SQL 结构、补列、索引、权限种子集中维护在 `YumiNail-Core/src/main/resources/files/YumiNail.sql`,同时关注 `scripts/sql/init/YumiNail.sql`。 +- 生产/开发密钥不写入仓库;Nacos、OSS、数据库凭据只能走配置中心或用户提供。 +- 用户可见文案用中文。 + +## 4. 当前状态快照 + +详细见 `CURRENT-STATE.md`。最重要的几条: + +- 工作区未提交:文件存储新增阿里云 OSS 备份链路,涉及 `modules/file`、`RabbitMQConfig`、SQL 和测试。 +- OSS 备份代码已在本地,但 Nacos 中 `aliyun.oss.enabled=false`,缺阿里云 endpoint、region、AK、SK。 +- 真实上传/签名预览已通过 MinIO,预览产物在 `artifacts/real-upload-signed-preview.png`。 +- 2026-06-05 已修 Nacos 命名问题:`yuminail-gateway.yaml`、`rabbitmq.yaml`、`yuminail-core` 已补齐。 +- Core/Gateway 生产服务已启动:`yumi-nail-core` 3 个健康实例,`yuminail-gateway` 3 个健康实例,均注册 80 端口。 +- datasource 临时直连 `mysql02:3306`,因为 `mysql-writer:3308` JDBC 握手失败;长期应修复 HA writer 后切回。 + +## 5. 常用验证命令 + +后端 Core: + +```powershell +rtk mvn test +rtk mvn -q -DskipTests compile +``` + +Gateway: + +```powershell +rtk mvn -q -DskipTests compile +``` + +Web: + +```powershell +rtk npm run build +``` + +小程序 JS 基础检查: + +```powershell +rtk powershell -NoProfile -Command '& { Get-ChildItem -LiteralPath "WeChatProgram" -Recurse -Filter "*.js" | ForEach-Object { node --check $_.FullName } }' +``` + +指尖管理师小程序优先用 `wechat-devtools-mcp` 做页面基础测试。 + +## 6. 下一步读取策略 + +- 继续当前 OSS/文件上传任务:读 `CURRENT-STATE.md`、`CORE-MODULES.md` 的 `file` 部分、`TASK-PLAYBOOKS.md` 的真实上传联调。 +- 改后端接口:读 `CORE-MODULES.md` 和 `TASK-PLAYBOOKS.md`。 +- 改前端或小程序:读 `PROJECT-MAP.md` 和 `TASK-PLAYBOOKS.md`。 +- 改 SQL、Nacos、生产服务:读 `CURRENT-STATE.md`、`RISK-REGISTER.md`。 +- 不确定读什么:先运行 `git status --short`,再用 `rg` 定位任务关键词。 + +## 7. 交接探针 + +新会话读完本文件后应能回答: + +- 项目有哪些子系统? +- 后端业务代码按什么模块找? +- 当前未提交的主要改动是什么? +- 修改代码前必须做什么? +- 当前 Nacos、数据库、OSS 的关键状态是什么? + diff --git a/docx/handoff/NEXT-SESSION-PROMPT.md b/docx/handoff/NEXT-SESSION-PROMPT.md new file mode 100644 index 00000000..8010fb46 --- /dev/null +++ b/docx/handoff/NEXT-SESSION-PROMPT.md @@ -0,0 +1,8 @@ +# Next Session Prompt + +复制下面这段给新会话: + +```text +你在 E:\code\xiaowang 工作。先读 AGENTS.md 和 docx/handoff/HANDOFF-BOOT.md,建立最小上下文;不要把 docx/README.md 或 docx/MEMORY.md 当首读资料。先运行 git status --short,不要回滚未提交改动。根据我的具体任务,只读取 docx/handoff/ 下相关附录;修改函数/类/方法前遵守 GitNexus impact,提交前遵守 detect_changes。 +``` + diff --git a/docx/handoff/PROJECT-MAP.md b/docx/handoff/PROJECT-MAP.md new file mode 100644 index 00000000..91709168 --- /dev/null +++ b/docx/handoff/PROJECT-MAP.md @@ -0,0 +1,116 @@ +# Project Map + +用途:任务命中具体子系统时读取。这里写入口和边界,不替代源码。 + +## YumiNail-Core + +职责:核心业务后端,Spring Boot 2.7.18,MyBatis-Plus,Redis,RabbitMQ,MinIO,OSS,Nacos。 + +关键入口: + +- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/YumiNailCoreApplication.java` +- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/modules` +- `YumiNail-Core/src/main/java/com/xiaowang/yuminailcore/config` +- `YumiNail-Core/src/main/resources/files/YumiNail.sql` + +边界: + +- 不要往旧的根级 `controller/dto/entity/mapper/service/vo` 新增业务代码。 +- 新业务优先放入现有 `modules.`。 +- SQL 结构变更集中维护初始化 SQL。 + +## YumiNail-Gateway + +职责:统一 API 入口,处理 `/api/**`、后台兼容路由、白名单和 Token 初筛。 + +关键入口: + +- `YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/YumiNailGatewayApplication.java` +- `YumiNail-Gateway/src/main/java/com/xiaowang/yumitailgateway/filter/AuthGlobalFilter.java` +- `YumiNail-Gateway/src/main/resources/bootstrap.yaml` +- Nacos `YumiNail / DEFAULT_GROUP / yuminail-gateway.yaml` + +边界: + +- 新增公开接口时,同时检查 Gateway 白名单和前端免登录路径。 +- Gateway 不应承载业务写逻辑。 + +## YumiNail-Frontend + +职责:Vue 3 Web 用户端和后台管理端。 + +关键入口: + +- `YumiNail-Frontend/src/main.ts` +- `YumiNail-Frontend/src/router` +- `YumiNail-Frontend/src/api` +- `YumiNail-Frontend/src/views` +- `YumiNail-Frontend/src/views/admin` + +边界: + +- 用户可见文案使用中文。 +- UI 偏柔和浅粉白,不要突然改成大面积蓝紫灰棕。 +- 前后台 token 独立,避免互相清理登录态。 + +## WeChatProgram + +职责:普通用户微信小程序,覆盖浏览、收藏、购物车、下单、订单、评价、我的等链路。 + +关键入口: + +- `WeChatProgram/app.json` +- `WeChatProgram/pages` +- `WeChatProgram/api` +- `WeChatProgram/utils/request.js` + +边界: + +- 匿名可浏览作品/店铺/详情。 +- 收藏、加购、下单、评价等动作需要登录。 + +## FingertipManager-Program + +职责:指尖管理师店长端排班小程序,服务规划、客户、员工、我的。 + +关键入口: + +- `FingertipManager-Program/app.json` +- `FingertipManager-Program/pages` +- `FingertipManager-Program/utils` +- `FingertipManager-Program/project.config.json` + +边界: + +- 这是全新的店长日历排班子系统,不迁回旧后台大表/营销/库存入口。 +- 月视图必须一眼看到每日各美甲师单量。 +- 页面测试优先使用 `wechat-devtools-mcp`。 + +## scripts/sql + +职责:SQL 初始化和辅助脚本。 + +关键入口: + +- `scripts/sql/init/YumiNail.sql` +- `YumiNail-Core/src/main/resources/files/YumiNail.sql` + +边界: + +- 两份初始化 SQL 需要保持一致或明确用途差异。 +- 真实数据库 DDL 优先使用 MySQL MCP;没有权限时说明阻塞。 + +## docx + +职责:项目说明、设计、测试案例、交接资料。 + +关键入口: + +- `docx/handoff/HANDOFF-BOOT.md` +- `docx/testing/yuminail-full-regression-test-cases.md` +- `docx/design` + +边界: + +- `docx/README.md`、`docx/MEMORY.md` 存在乱码,不作为首读。 + diff --git a/docx/handoff/RISK-REGISTER.md b/docx/handoff/RISK-REGISTER.md new file mode 100644 index 00000000..fcc7c46d --- /dev/null +++ b/docx/handoff/RISK-REGISTER.md @@ -0,0 +1,99 @@ +# Risk Register + +用途:修改高风险区域前读取。 + +## GitNexus + +风险:修改函数、类、方法前未做 impact,容易破坏隐藏调用链。 + +检查点: + +- 改 symbol 前运行 GitNexus upstream impact。 +- 高/关键风险先告知用户。 +- 提交前运行 GitNexus detect_changes。 + +## 脏工作区 + +风险:仓库经常有未提交改动,回滚会丢用户或前序任务成果。 + +检查点: + +- 每次开工先 `git status --short`。 +- 只改当前任务相关文件。 +- 不使用 `git reset --hard`、`git checkout --` 回滚未授权改动。 + +## SQL + +风险:散落 SQL 会导致初始化库、真实库、测试库不一致。 + +检查点: + +- 结构、补列、索引、权限种子优先更新 `YumiNail-Core/src/main/resources/files/YumiNail.sql`。 +- 同步关注 `scripts/sql/init/YumiNail.sql`。 +- 真实 DDL 优先 MySQL MCP,不能执行就记录阻塞。 + +## MinIO / OSS + +风险:MinIO 是主上传链路;OSS 只是异步备份和展示回退。混淆会导致上传不可控。 + +检查点: + +- 上传仍优先 MinIO,MinIO 失败则上传失败。 +- OSS 备份不能阻塞主流程。 +- OSS 私有桶必须返回签名 URL,不返回裸链接。 +- 当前 OSS 缺配置,`aliyun.oss.enabled=false`。 + +## Nacos / RabbitMQ + +风险:dataId 命名历史不一致导致服务启动时读空配置。 + +检查点: + +- Core 使用 `rabbit-mq.yaml`。 +- Gateway 使用 `rabbitmq.yaml`。 +- 当前两个 dataId 都已补齐。 +- Gateway 主配置同时存在 `yuminail-gateway` 和 `yuminail-gateway.yaml`。 +- Core 主配置同时存在 `yuminail-core` 和 `yuminail-core.yaml`。 + +## MySQL Writer + +风险:当前 datasource 临时直连 `mysql02:3306`,不具备主库自动切换能力。 + +检查点: + +- 不要误以为这是最终架构。 +- 长期修复目标是恢复 `mysql-writer:3308` JDBC 可用。 +- 切回 writer 前验证 `read_only=0`、`super_read_only=0`。 + +## 店铺授权 + +风险:店铺到期是动态冻结,不应简单改 `status`。 + +检查点: + +- `t_shop.authorization_expire_time` 为空代表长期有效。 +- 到期后前台提示冻结,后台可登录但业务功能受限。 + +## 身份和权限 + +风险:店长、美甲师、平台管理员、店铺自定义角色权限边界容易混。 + +检查点: + +- 店长 `type=2`。 +- 美甲师 `type=3`。 +- 平台管理员 `type=4`。 +- 店长参与制作由 `t_nail_artist_info.participate_production` 控制。 +- 店铺自定义角色权限按当前 `currentShopId` 生效。 + +## 预约和订单 + +风险:绕过容量/占用/状态机会造成重复预约、释放失败或并发错乱。 + +检查点: + +- 新建/改派/改时间必须校验营业时间、排班、容量、已有占用。 +- 订单状态流转优先使用既有状态机和条件更新。 +- 取消订单要释放预约占用。 +- YumiNail 已确认订单应进入指尖管理师规划。 + diff --git a/docx/handoff/TASK-PLAYBOOKS.md b/docx/handoff/TASK-PLAYBOOKS.md new file mode 100644 index 00000000..f9cd5c44 --- /dev/null +++ b/docx/handoff/TASK-PLAYBOOKS.md @@ -0,0 +1,144 @@ +# Task Playbooks + +用途:按任务类型走最短路径,减少新会话重复探索。 + +## 改后端接口 + +先读: + +- `HANDOFF-BOOT.md` +- `CORE-MODULES.md` +- `RISK-REGISTER.md` + +步骤: + +1. `git status --short`,确认脏工作区。 +2. 用 `rg` 或 GitNexus query 定位模块。 +3. 修改 symbol 前做 GitNexus upstream impact。 +4. 按模块局部结构改 controller/service/dto/vo/mapper/entity。 +5. 跑相关测试或 `rtk mvn -q -DskipTests compile`。 +6. 涉及提交前跑 GitNexus detect_changes。 + +容易漏: + +- Gateway 白名单。 +- 前端免登录路径。 +- SQL 初始化脚本。 +- 店铺作用域和权限码。 + +## 改前端页面 + +先读: + +- `PROJECT-MAP.md` +- 相关 `YumiNail-Frontend/src/api` 和 `src/views`。 + +步骤: + +1. 查路由和 API 封装。 +2. 保持中文文案和现有 UI 风格。 +3. 修改后跑 `rtk npm run build`。 + +容易漏: + +- 前后台 token 独立。 +- 免登录接口 401 不应触发全局过期跳转。 + +## 改微信用户小程序 + +先读: + +- `PROJECT-MAP.md` +- `WeChatProgram/app.json` +- `WeChatProgram/utils/request.js` + +步骤: + +1. 查页面路径和 API。 +2. 保持匿名浏览能力。 +3. JS 改动后跑 node 语法检查。 + +容易漏: + +- 弹窗遮罩才使用 `catchtouchmove`。 +- 小屏需要可滚动。 + +## 改指尖管理师小程序 + +先读: + +- `PROJECT-MAP.md` +- `FingertipManager-Program/app.json` + +步骤: + +1. 优先检查规划、客户、员工、我的四个 Tab。 +2. 月视图必须直接展示各美甲师单量。 +3. 页面测试用 `wechat-devtools-mcp`。 + +容易漏: + +- 不要恢复旧后台营销/库存/权限大表入口。 +- 固定底部按钮和 TabBar 不要遮挡内容。 + +## 改 SQL / 初始化数据 + +先读: + +- `RISK-REGISTER.md` +- `CURRENT-STATE.md` + +步骤: + +1. 更新 `YumiNail-Core/src/main/resources/files/YumiNail.sql`。 +2. 同步 `scripts/sql/init/YumiNail.sql`。 +3. 用 schema 测试或 MySQL MCP 验证列和索引。 + +容易漏: + +- 真实库已可能手工补过列,不能只看本地 SQL。 + +## 改 Nacos / 生产服务 + +先读: + +- `CURRENT-STATE.md` +- `RISK-REGISTER.md` + +步骤: + +1. 只读检查命名空间、dataId、实例。 +2. 写配置前备份原配置。 +3. 不写明文密钥到仓库。 +4. 发布后检查服务日志和 Nacos 实例健康。 + +容易漏: + +- Core/Gateway 读不同 RabbitMQ dataId。 +- `mysql02:3306` 是临时直连,不是最终 HA writer。 + +## 做真实上传 / 预约 / 订单联调 + +先读: + +- `CURRENT-STATE.md` +- `CORE-MODULES.md` + +上传联调: + +1. 确认 MinIO 可用。 +2. 上传后检查文件表 MinIO 状态。 +3. OSS 配好后检查 MQ 备份状态和 OSS 签名 URL。 +4. MinIO 故障回退只验证已备份成功文件。 + +预约/订单联调: + +1. 准备店铺、作品、美甲师、排班。 +2. 用户下单/店长确认后检查预约占用。 +3. 指尖管理师新建/改派/取消检查冲突和释放。 + +容易漏: + +- OSS 未配置时不要期望备份成功。 +- 预约必须校验营业时间、排班、容量、已有占用。 + diff --git a/scripts/sql/init/YumiNail.sql b/scripts/sql/init/YumiNail.sql index 483eb459..e1e6eeba 100644 --- a/scripts/sql/init/YumiNail.sql +++ b/scripts/sql/init/YumiNail.sql @@ -276,6 +276,17 @@ create table t_object_storage_file primary key comment '对象存储文件主键索引', file_name varchar(100) not null comment '文件名称', file_url text not null comment '文件访问链接', + object_name varchar(512) null comment '对象存储Key', + minio_url text null comment 'MinIO访问链接', + oss_url text null comment '阿里云OSS内部备份链接', + content_type varchar(128) null comment '文件Content-Type', + file_size bigint unsigned null comment '文件大小,单位字节', + minio_upload_status tinyint unsigned default 0 not null comment 'MinIO上传状态:0-PENDING,1-SUCCEEDED,2-FAILED', + oss_upload_status tinyint unsigned default 0 not null comment 'OSS上传状态:0-PENDING,1-SUCCEEDED,2-FAILED', + oss_retry_count int unsigned default 0 not null comment 'OSS备份重试次数', + oss_last_error varchar(500) null comment '最近一次OSS备份失败原因', + oss_uploaded_at datetime null comment 'OSS备份成功时间', + oss_last_retry_time datetime null comment '最近一次OSS备份重试时间', create_time datetime default CURRENT_TIMESTAMP not null comment '文件上传时间', update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '文件更新时间', status tinyint unsigned default 1 null comment '文件状态:1-可用,0-不可用,2-回收站', @@ -288,6 +299,10 @@ create index idx_status on t_object_storage_file (status) comment '按文件状态查询的索引'; +create index idx_object_storage_file_oss_retry + on t_object_storage_file (oss_upload_status, minio_upload_status, status) + comment 'OSS备份失败重试扫描索引'; + -- auto-generated definition create table t_order ( @@ -920,6 +935,25 @@ CALL sp_add_column_if_not_exists('t_balance', 'total_recharge_amount', 'decimal( CALL sp_add_column_if_not_exists('t_balance', 'last_recharge_time', 'datetime NULL COMMENT ''最近一次充值时间'''); CALL sp_add_column_if_not_exists('t_balance', 'update_time', 'datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT ''更新时间'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'object_name', 'varchar(512) NULL COMMENT ''对象存储Key'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'minio_url', 'text NULL COMMENT ''MinIO访问链接'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_url', 'text NULL COMMENT ''阿里云OSS内部备份链接'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'content_type', 'varchar(128) NULL COMMENT ''文件Content-Type'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'file_size', 'bigint unsigned NULL COMMENT ''文件大小,单位字节'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'minio_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''MinIO上传状态:0-PENDING,1-SUCCEEDED,2-FAILED'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_upload_status', 'tinyint unsigned NOT NULL DEFAULT 0 COMMENT ''OSS上传状态:0-PENDING,1-SUCCEEDED,2-FAILED'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_retry_count', 'int unsigned NOT NULL DEFAULT 0 COMMENT ''OSS备份重试次数'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_last_error', 'varchar(500) NULL COMMENT ''最近一次OSS备份失败原因'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_uploaded_at', 'datetime NULL COMMENT ''OSS备份成功时间'''); +CALL sp_add_column_if_not_exists('t_object_storage_file', 'oss_last_retry_time', 'datetime NULL COMMENT ''最近一次OSS备份重试时间'''); +UPDATE t_object_storage_file +SET minio_url = COALESCE(minio_url, file_url), + minio_upload_status = CASE WHEN minio_upload_status IS NULL OR minio_upload_status = 0 THEN 1 ELSE minio_upload_status END, + oss_upload_status = COALESCE(oss_upload_status, 0), + oss_retry_count = COALESCE(oss_retry_count, 0) +WHERE status = 1; +CALL sp_add_index_if_not_exists('t_object_storage_file', 'idx_object_storage_file_oss_retry', '(`oss_upload_status`, `minio_upload_status`, `status`)'); + UPDATE t_balance SET total_recharge_amount = COALESCE(total_recharge_amount, 0.00) WHERE total_recharge_amount IS NULL;