fix(inventory): 控制照片上传占用并记录存储故障
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
This commit is contained in:
parent
8ca4b3bb79
commit
c256408078
|
|
@ -6,7 +6,6 @@ import java.awt.RenderingHints;
|
||||||
import java.awt.image.BufferedImage;
|
import java.awt.image.BufferedImage;
|
||||||
import java.io.ByteArrayOutputStream;
|
import java.io.ByteArrayOutputStream;
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
import java.util.concurrent.Semaphore;
|
|
||||||
import javax.imageio.IIOImage;
|
import javax.imageio.IIOImage;
|
||||||
import javax.imageio.ImageIO;
|
import javax.imageio.ImageIO;
|
||||||
import javax.imageio.ImageWriteParam;
|
import javax.imageio.ImageWriteParam;
|
||||||
|
|
@ -18,7 +17,6 @@ import org.springframework.web.server.ResponseStatusException;
|
||||||
final class PhotoImages {
|
final class PhotoImages {
|
||||||
private static final int MAX_BYTES = 5 * 1024 * 1024;
|
private static final int MAX_BYTES = 5 * 1024 * 1024;
|
||||||
private static final int MAX_SIDE = 2048;
|
private static final int MAX_SIDE = 2048;
|
||||||
private static final Semaphore DECODERS = new Semaphore(2);
|
|
||||||
|
|
||||||
record Encoded(byte[] image, byte[] thumbnail) {}
|
record Encoded(byte[] image, byte[] thumbnail) {}
|
||||||
|
|
||||||
|
|
@ -26,9 +24,6 @@ final class PhotoImages {
|
||||||
if (file.getSize() > MAX_BYTES) {
|
if (file.getSize() > MAX_BYTES) {
|
||||||
throw new ResponseStatusException(CONTENT_TOO_LARGE, "图片不能超过 5 MiB");
|
throw new ResponseStatusException(CONTENT_TOO_LARGE, "图片不能超过 5 MiB");
|
||||||
}
|
}
|
||||||
if (!DECODERS.tryAcquire()) {
|
|
||||||
throw new ResponseStatusException(SERVICE_UNAVAILABLE, "正在处理图片,请稍后重试");
|
|
||||||
}
|
|
||||||
try (var source = file.getInputStream(); var input = new MemoryCacheImageInputStream(source)) {
|
try (var source = file.getInputStream(); var input = new MemoryCacheImageInputStream(source)) {
|
||||||
var readers = ImageIO.getImageReaders(input);
|
var readers = ImageIO.getImageReaders(input);
|
||||||
if (!readers.hasNext()) { throw invalid(); }
|
if (!readers.hasNext()) { throw invalid(); }
|
||||||
|
|
@ -44,7 +39,7 @@ final class PhotoImages {
|
||||||
} finally { reader.dispose(); }
|
} finally { reader.dispose(); }
|
||||||
} catch (IOException | IllegalArgumentException ex) {
|
} catch (IOException | IllegalArgumentException ex) {
|
||||||
throw invalid();
|
throw invalid();
|
||||||
} finally { DECODERS.release(); }
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private static ResponseStatusException invalid() {
|
private static ResponseStatusException invalid() {
|
||||||
|
|
@ -55,12 +50,17 @@ final class PhotoImages {
|
||||||
double scale = Math.min(1, (double) maxSide / Math.max(source.getWidth(), source.getHeight()));
|
double scale = Math.min(1, (double) maxSide / Math.max(source.getWidth(), source.getHeight()));
|
||||||
int width = Math.max(1, (int) Math.round(source.getWidth() * scale));
|
int width = Math.max(1, (int) Math.round(source.getWidth() * scale));
|
||||||
int height = Math.max(1, (int) Math.round(source.getHeight() * scale));
|
int height = Math.max(1, (int) Math.round(source.getHeight() * scale));
|
||||||
var image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
BufferedImage image = source;
|
||||||
var graphics = image.createGraphics();
|
boolean standardRgb = (source.getType() == BufferedImage.TYPE_3BYTE_BGR
|
||||||
try {
|
|| source.getType() == BufferedImage.TYPE_INT_RGB) && source.getColorModel().getColorSpace().isCS_sRGB();
|
||||||
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
if (scale < 1 || !standardRgb) {
|
||||||
graphics.drawImage(source, 0, 0, width, height, null);
|
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||||
} finally { graphics.dispose(); }
|
var graphics = image.createGraphics();
|
||||||
|
try {
|
||||||
|
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
|
||||||
|
graphics.drawImage(source, 0, 0, width, height, null);
|
||||||
|
} finally { graphics.dispose(); }
|
||||||
|
}
|
||||||
var writer = ImageIO.getImageWritersByFormatName("jpeg").next();
|
var writer = ImageIO.getImageWritersByFormatName("jpeg").next();
|
||||||
var bytes = new ByteArrayOutputStream();
|
var bytes = new ByteArrayOutputStream();
|
||||||
try (var output = new MemoryCacheImageOutputStream(bytes)) {
|
try (var output = new MemoryCacheImageOutputStream(bytes)) {
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@ import java.time.OffsetDateTime;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.UUID;
|
import java.util.UUID;
|
||||||
|
import java.util.concurrent.Semaphore;
|
||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.ObjectProvider;
|
import org.springframework.beans.factory.ObjectProvider;
|
||||||
|
|
@ -25,11 +26,13 @@ import software.amazon.awssdk.core.exception.SdkException;
|
||||||
@Service
|
@Service
|
||||||
class PhotoService {
|
class PhotoService {
|
||||||
private static final Logger log = LoggerFactory.getLogger(PhotoService.class);
|
private static final Logger log = LoggerFactory.getLogger(PhotoService.class);
|
||||||
|
private static final int UPLOAD_CAPACITY = 2;
|
||||||
private final JdbcClient db;
|
private final JdbcClient db;
|
||||||
private final HouseholdAccess access;
|
private final HouseholdAccess access;
|
||||||
private final PhotoStorage storage;
|
private final PhotoStorage storage;
|
||||||
private final TransactionTemplate transaction;
|
private final TransactionTemplate transaction;
|
||||||
private final MeterRegistry metrics;
|
private final MeterRegistry metrics;
|
||||||
|
private final Semaphore uploads = new Semaphore(UPLOAD_CAPACITY);
|
||||||
|
|
||||||
PhotoService(JdbcClient db, HouseholdAccess access, ObjectProvider<PhotoStorage> storage,
|
PhotoService(JdbcClient db, HouseholdAccess access, ObjectProvider<PhotoStorage> storage,
|
||||||
PlatformTransactionManager manager, MeterRegistry metrics) {
|
PlatformTransactionManager manager, MeterRegistry metrics) {
|
||||||
|
|
@ -40,6 +43,7 @@ class PhotoService {
|
||||||
this.metrics = metrics;
|
this.metrics = metrics;
|
||||||
metrics.gauge("atlas.media.cleanup.pending", db,
|
metrics.gauge("atlas.media.cleanup.pending", db,
|
||||||
jdbc -> jdbc.sql("SELECT count(*) FROM media_cleanup").query(Long.class).single());
|
jdbc -> jdbc.sql("SELECT count(*) FROM media_cleanup").query(Long.class).single());
|
||||||
|
metrics.gauge("atlas.media.upload.active", uploads, permits -> UPLOAD_CAPACITY - permits.availablePermits());
|
||||||
}
|
}
|
||||||
|
|
||||||
record Photo(UUID id) {}
|
record Photo(UUID id) {}
|
||||||
|
|
@ -92,7 +96,18 @@ class PhotoService {
|
||||||
var existing = uploaded(household, target, entity, actor, requestKey);
|
var existing = uploaded(household, target, entity, actor, requestKey);
|
||||||
if (existing.isPresent()) { return existing.get(); }
|
if (existing.isPresent()) { return existing.get(); }
|
||||||
requireStorage();
|
requireStorage();
|
||||||
var images = PhotoImages.encode(file);
|
// Keep the permit through the S3 writes so slow storage cannot queue encoded images in memory.
|
||||||
|
if (!uploads.tryAcquire()) {
|
||||||
|
metrics.counter("atlas.media.upload.rejected", "reason", "busy").increment();
|
||||||
|
throw new ResponseStatusException(SERVICE_UNAVAILABLE, "正在处理图片,请稍后重试");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return storePhoto(household, target, entity, actor, PhotoImages.encode(file), requestKey);
|
||||||
|
} finally { uploads.release(); }
|
||||||
|
}
|
||||||
|
|
||||||
|
private Photo storePhoto(UUID household, Target target, UUID entity, String actor,
|
||||||
|
PhotoImages.Encoded images, UUID requestKey) {
|
||||||
UUID id = UUID.randomUUID();
|
UUID id = UUID.randomUUID();
|
||||||
String prefix = "households/" + household + "/" + target.collection + "/" + entity + "/" + id;
|
String prefix = "households/" + household + "/" + target.collection + "/" + entity + "/" + id;
|
||||||
transaction.executeWithoutResult(status -> {
|
transaction.executeWithoutResult(status -> {
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,16 @@
|
||||||
package com.tutudog.itematlas.inventory;
|
package com.tutudog.itematlas.inventory;
|
||||||
|
|
||||||
|
import io.micrometer.core.instrument.MeterRegistry;
|
||||||
|
import io.micrometer.core.instrument.Timer;
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
import java.net.ConnectException;
|
||||||
|
import java.net.SocketTimeoutException;
|
||||||
import java.net.URI;
|
import java.net.URI;
|
||||||
|
import java.net.UnknownHostException;
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
@ -11,10 +20,14 @@ import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
|
||||||
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
|
||||||
import software.amazon.awssdk.core.checksums.RequestChecksumCalculation;
|
import software.amazon.awssdk.core.checksums.RequestChecksumCalculation;
|
||||||
import software.amazon.awssdk.core.checksums.ResponseChecksumValidation;
|
import software.amazon.awssdk.core.checksums.ResponseChecksumValidation;
|
||||||
|
import software.amazon.awssdk.core.exception.ApiCallAttemptTimeoutException;
|
||||||
|
import software.amazon.awssdk.core.exception.ApiCallTimeoutException;
|
||||||
|
import software.amazon.awssdk.core.exception.SdkException;
|
||||||
import software.amazon.awssdk.core.sync.RequestBody;
|
import software.amazon.awssdk.core.sync.RequestBody;
|
||||||
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
|
||||||
import software.amazon.awssdk.regions.Region;
|
import software.amazon.awssdk.regions.Region;
|
||||||
import software.amazon.awssdk.services.s3.S3Client;
|
import software.amazon.awssdk.services.s3.S3Client;
|
||||||
|
import software.amazon.awssdk.services.s3.model.S3Exception;
|
||||||
|
|
||||||
@Configuration(proxyBeanMethods = false)
|
@Configuration(proxyBeanMethods = false)
|
||||||
@EnableScheduling
|
@EnableScheduling
|
||||||
|
|
@ -23,16 +36,21 @@ class MediaScheduling {}
|
||||||
@Component
|
@Component
|
||||||
@ConditionalOnExpression("T(org.springframework.util.StringUtils).hasText('${atlas.media.endpoint:}')")
|
@ConditionalOnExpression("T(org.springframework.util.StringUtils).hasText('${atlas.media.endpoint:}')")
|
||||||
class PhotoStorage implements AutoCloseable {
|
class PhotoStorage implements AutoCloseable {
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(PhotoStorage.class);
|
||||||
|
private static final String CONTENT_TYPE = "image/jpeg";
|
||||||
private final S3Client client;
|
private final S3Client client;
|
||||||
private final String bucket;
|
private final String bucket;
|
||||||
|
private final MeterRegistry metrics;
|
||||||
|
|
||||||
PhotoStorage(@Value("${atlas.media.endpoint}") URI endpoint, @Value("${atlas.media.bucket}") String bucket,
|
PhotoStorage(@Value("${atlas.media.endpoint}") URI endpoint, @Value("${atlas.media.bucket}") String bucket,
|
||||||
@Value("${atlas.media.region}") String region, @Value("${atlas.media.path-style}") boolean pathStyle,
|
@Value("${atlas.media.region}") String region, @Value("${atlas.media.path-style}") boolean pathStyle,
|
||||||
@Value("${atlas.media.access-key}") String access, @Value("${atlas.media.secret-key}") String secret) {
|
@Value("${atlas.media.access-key}") String access, @Value("${atlas.media.secret-key}") String secret,
|
||||||
|
MeterRegistry metrics) {
|
||||||
if (bucket.isBlank() || access.isBlank() || secret.isBlank()) {
|
if (bucket.isBlank() || access.isBlank() || secret.isBlank()) {
|
||||||
throw new IllegalArgumentException("Media bucket and credentials are required when storage is enabled");
|
throw new IllegalArgumentException("Media bucket and credentials are required when storage is enabled");
|
||||||
}
|
}
|
||||||
this.bucket = bucket;
|
this.bucket = bucket;
|
||||||
|
this.metrics = metrics;
|
||||||
client = S3Client.builder().endpointOverride(endpoint).region(Region.of(region)).forcePathStyle(pathStyle)
|
client = S3Client.builder().endpointOverride(endpoint).region(Region.of(region)).forcePathStyle(pathStyle)
|
||||||
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(access, secret)))
|
.credentialsProvider(StaticCredentialsProvider.create(AwsBasicCredentials.create(access, secret)))
|
||||||
.requestChecksumCalculation(RequestChecksumCalculation.WHEN_REQUIRED)
|
.requestChecksumCalculation(RequestChecksumCalculation.WHEN_REQUIRED)
|
||||||
|
|
@ -44,23 +62,67 @@ class PhotoStorage implements AutoCloseable {
|
||||||
}
|
}
|
||||||
|
|
||||||
void store(String prefix, PhotoImages.Encoded images) {
|
void store(String prefix, PhotoImages.Encoded images) {
|
||||||
put(prefix + "/image.jpg", images.image());
|
put(prefix, false, images.image());
|
||||||
put(prefix + "/thumb.jpg", images.thumbnail());
|
put(prefix, true, images.thumbnail());
|
||||||
}
|
}
|
||||||
|
|
||||||
byte[] get(String prefix, boolean thumbnail) {
|
byte[] get(String prefix, boolean thumbnail) {
|
||||||
return client.getObjectAsBytes(request -> request.bucket(bucket)
|
return observe("get", thumbnail, () -> client.getObjectAsBytes(request -> request.bucket(bucket)
|
||||||
.key(prefix + (thumbnail ? "/thumb.jpg" : "/image.jpg"))).asByteArray();
|
.key(objectKey(prefix, thumbnail))).asByteArray());
|
||||||
}
|
}
|
||||||
|
|
||||||
void delete(String prefix) {
|
void delete(String prefix) {
|
||||||
client.deleteObject(request -> request.bucket(bucket).key(prefix + "/image.jpg"));
|
delete(prefix, false);
|
||||||
client.deleteObject(request -> request.bucket(bucket).key(prefix + "/thumb.jpg"));
|
delete(prefix, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
private void put(String key, byte[] data) {
|
private void delete(String prefix, boolean thumbnail) {
|
||||||
client.putObject(request -> request.bucket(bucket).key(key).contentType("image/jpeg"),
|
observe("delete", thumbnail, () -> client.deleteObject(request -> request.bucket(bucket)
|
||||||
RequestBody.fromBytes(data));
|
.key(objectKey(prefix, thumbnail))));
|
||||||
|
}
|
||||||
|
|
||||||
|
private void put(String prefix, boolean thumbnail, byte[] data) {
|
||||||
|
// The encoder owns these bytes. Reopen the stream on retry without copying the array.
|
||||||
|
var body = RequestBody.fromContentProvider(() -> new ByteArrayInputStream(data), data.length, CONTENT_TYPE);
|
||||||
|
observe("put", thumbnail, () -> client.putObject(request -> request.bucket(bucket)
|
||||||
|
.key(objectKey(prefix, thumbnail)).contentType(CONTENT_TYPE), body));
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String objectKey(String prefix, boolean thumbnail) {
|
||||||
|
return prefix + (thumbnail ? "/thumb.jpg" : "/image.jpg");
|
||||||
|
}
|
||||||
|
|
||||||
|
private <T> T observe(String operation, boolean thumbnail, Supplier<T> request) {
|
||||||
|
var sample = Timer.start(metrics);
|
||||||
|
String variant = thumbnail ? "thumbnail" : "original";
|
||||||
|
String outcome = "error";
|
||||||
|
try {
|
||||||
|
T result = request.get();
|
||||||
|
outcome = "success";
|
||||||
|
return result;
|
||||||
|
} catch (SdkException failure) {
|
||||||
|
outcome = failureType(failure);
|
||||||
|
if ("put".equals(operation)) {
|
||||||
|
log.warn("Photo storage upload failed (variant {}, outcome {})", variant, outcome);
|
||||||
|
}
|
||||||
|
throw failure;
|
||||||
|
} finally {
|
||||||
|
sample.stop(metrics.timer("atlas.media.storage.requests",
|
||||||
|
"operation", operation, "variant", variant, "outcome", outcome));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static String failureType(SdkException failure) {
|
||||||
|
if (failure instanceof S3Exception response) {
|
||||||
|
if (response.statusCode() >= 500) { return "s3_5xx"; }
|
||||||
|
if (response.statusCode() >= 400) { return "s3_4xx"; }
|
||||||
|
}
|
||||||
|
for (Throwable cause = failure; cause != null; cause = cause.getCause()) {
|
||||||
|
if (cause instanceof ApiCallTimeoutException || cause instanceof ApiCallAttemptTimeoutException
|
||||||
|
|| cause instanceof SocketTimeoutException) { return "timeout"; }
|
||||||
|
if (cause instanceof ConnectException || cause instanceof UnknownHostException) { return "connection"; }
|
||||||
|
}
|
||||||
|
return "error";
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override public void close() { client.close(); }
|
@Override public void close() { client.close(); }
|
||||||
|
|
|
||||||
|
|
@ -121,6 +121,9 @@ def main():
|
||||||
import json
|
import json
|
||||||
|
|
||||||
jpeg = Path(os.environ["ATLAS_SMOKE_JPEG"]).read_bytes()
|
jpeg = Path(os.environ["ATLAS_SMOKE_JPEG"]).read_bytes()
|
||||||
|
assert jpeg.startswith(b"\xff\xd8")
|
||||||
|
marker = b"Item Atlas synthetic private metadata"
|
||||||
|
jpeg = jpeg[:2] + b"\xff\xe1" + (len(marker) + 2).to_bytes(2, "big") + marker + jpeg[2:]
|
||||||
house = call("POST", "/api/households", {"name": "图片验收", "displayName": "测试"}, status=201)["id"]
|
house = call("POST", "/api/households", {"name": "图片验收", "displayName": "测试"}, status=201)["id"]
|
||||||
space = f"/api/households/{house}"
|
space = f"/api/households/{house}"
|
||||||
location = call("POST", space + "/locations", {"name": "抽屉"}, status=201)["id"]
|
location = call("POST", space + "/locations", {"name": "抽屉"}, status=201)["id"]
|
||||||
|
|
@ -148,6 +151,7 @@ def main():
|
||||||
full = response(make_request("GET", resource, None, "owner"), 200)
|
full = response(make_request("GET", resource, None, "owner"), 200)
|
||||||
thumb = response(make_request("GET", resource + "?thumbnail=true", None, "viewer"), 200)
|
thumb = response(make_request("GET", resource + "?thumbnail=true", None, "viewer"), 200)
|
||||||
assert full[:2] == thumb[:2] == b"\xff\xd8" and len(full) > len(thumb)
|
assert full[:2] == thumb[:2] == b"\xff\xd8" and len(full) > len(thumb)
|
||||||
|
assert marker not in full and marker not in thumb, "Source JPEG metadata leaked into a stored image"
|
||||||
call("GET", resource, user="other", status=404)
|
call("GET", resource, user="other", status=404)
|
||||||
call("GET", resource, user=None, status=401)
|
call("GET", resource, user=None, status=401)
|
||||||
assert all(storage_status(house, item["id"], photo, variant) == "200" for variant in ("image.jpg", "thumb.jpg"))
|
assert all(storage_status(house, item["id"], photo, variant) == "200" for variant in ("image.jpg", "thumb.jpg"))
|
||||||
|
|
|
||||||
|
|
@ -67,10 +67,22 @@ Flyway V10 新增 `location_photo`,以空间和位置 ID 组成的外键约束
|
||||||
|
|
||||||
Bucket 关闭匿名访问,当前清理语义要求关闭版本保留和对象锁。开启这些能力前须另行定义版本删除及保留策略。Nginx 上传大小设为 `6m`,网关及 multipart 总上限 6 MiB,单图上限 5 MiB。后端按解码器校验 JPEG 和像素,最长边上限为 2048,重新编码时去掉图片元数据。每张图以独立 UUID 保存两份对象。读取经 API 校验当前成员身份,列表可以只请求最长边 320 像素的 `thumbnail=true` 响应。
|
Bucket 关闭匿名访问,当前清理语义要求关闭版本保留和对象锁。开启这些能力前须另行定义版本删除及保留策略。Nginx 上传大小设为 `6m`,网关及 multipart 总上限 6 MiB,单图上限 5 MiB。后端按解码器校验 JPEG 和像素,最长边上限为 2048,重新编码时去掉图片元数据。每张图以独立 UUID 保存两份对象。读取经 API 校验当前成员身份,列表可以只请求最长边 320 像素的 `thumbnail=true` 响应。
|
||||||
|
|
||||||
|
每个物品服务实例同时处理最多两张待写入的照片,名额从解码保留到对象写入和记录提交结束。占满后,新上传会立即返回 503 和「正在处理图片」提示,客户端可用原幂等键重试。已经保存的请求仍能直接查回原记录。兼容的 sRGB 原图直接重新编码,缩略图及需要转换的图像重新绘制。SDK 重试时从原编码缓冲区重新打开输入流。
|
||||||
|
|
||||||
物品照片使用 `households/{空间}/items/{物品}/{图片}/`,位置照片使用 `households/{空间}/locations/{位置}/{图片}/`。每张照片存 `image.jpg` 和 `thumb.jpg`。上传先提交清理预留,再写两个对象,成功后提交照片并取消预留。照片删除、物品归档、位置归档和空间删除由数据库触发器登记清理。空间删除立即撤销访问并移除空间数据,管理路径另外写审计。旧的批量录入审计仍在录入服务库,空间删除后接口会拒绝访问,录入审计保留策略需单独维护。
|
物品照片使用 `households/{空间}/items/{物品}/{图片}/`,位置照片使用 `households/{空间}/locations/{位置}/{图片}/`。每张照片存 `image.jpg` 和 `thumb.jpg`。上传先提交清理预留,再写两个对象,成功后提交照片并取消预留。照片删除、物品归档、位置归档和空间删除由数据库触发器登记清理。空间删除立即撤销访问并移除空间数据,管理路径另外写审计。旧的批量录入审计仍在录入服务库,空间删除后接口会拒绝访问,录入审计保留策略需单独维护。
|
||||||
|
|
||||||
清理任务在物品服务领取,利用 `FOR UPDATE SKIP LOCKED` 避免多个 Pod 重复领取,同一个对象可安全重删。丢失响应或 OSS 暂时不可用时,任务会退避后重试。观察 `atlas_media_cleanup_pending` 和 `atlas_media_cleanup_attempts_total{result="retry"}` 判断是否积压。网关和图片接口返回 `202` 表示删除已受理,核对物理删除请检查清理队列和两个对象键。
|
清理任务在物品服务领取,利用 `FOR UPDATE SKIP LOCKED` 避免多个 Pod 重复领取,同一个对象可安全重删。丢失响应或 OSS 暂时不可用时,任务会退避后重试。观察 `atlas_media_cleanup_pending` 和 `atlas_media_cleanup_attempts_total{result="retry"}` 判断是否积压。网关和图片接口返回 `202` 表示删除已受理,核对物理删除请检查清理队列和两个对象键。
|
||||||
|
|
||||||
|
上传返回 503 时,用 `atlas_media_upload_active` 查当前写入数,用 `increase(atlas_media_upload_rejected_total{reason="busy"}[5m])` 查超出并发上限的次数。如果接口提示图片存储暂不可用,按下面的查询区分请求阶段及结果。`operation` 为 `put`、`get` 或 `delete`,`variant` 为原图或缩略图。失败结果包含 `timeout`、`connection`、`s3_4xx`、`s3_5xx` 或未归类错误。上传失败日志记阶段和结果,日志字段不包含对象路径或请求凭据。
|
||||||
|
|
||||||
|
```promql
|
||||||
|
sum by (operation, variant, outcome) (
|
||||||
|
increase(atlas_media_storage_requests_seconds_count{outcome!="success"}[5m])
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
验收时在隔离环境阻塞两次 S3 写入,第三次应快速返回繁忙,已完成请求和查询仍可使用。再让原图写入成功、缩略图失败,确认照片列表没有新增记录,后台能清除半成品。同一幂等键重试成功后,列表应只有一条新记录。 [AWS SDK 超时](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/timeouts.html)
|
||||||
|
|
||||||
Flyway V4 为增量迁移。灰度前先让稳定版完成迁移,再启用读流量候选。图片操作与管理删除继续走稳定库存服务。回滚到旧镜像后恢复新版本的清理 worker 才会继续处理积压任务。
|
Flyway V4 为增量迁移。灰度前先让稳定版完成迁移,再启用读流量候选。图片操作与管理删除继续走稳定库存服务。回滚到旧镜像后恢复新版本的清理 worker 才会继续处理积压任务。
|
||||||
|
|
||||||
[Garage 单节点部署](https://garagehq.deuxfleurs.fr/documentation/quick-start/) · [AWS SDK S3 端点](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/endpoint-config.html)
|
[Garage 单节点部署](https://garagehq.deuxfleurs.fr/documentation/quick-start/) · [AWS SDK S3 端点](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/endpoint-config.html)
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue