Compare commits

...

2 Commits

Author SHA1 Message Date
dongjf 1928ed55d3 docs: 补齐部署搭建、架构和业务验收说明
continuous-integration/drone/push Build is passing Details
2026-11-25 15:02:22 +08:00
dongjf 0dfb0b656b feat: 补齐家庭建档、录入恢复和预发布监控
continuous-integration/drone/tag Build is passing Details
continuous-integration/drone Build is passing Details
2026-11-25 14:51:57 +08:00
41 changed files with 956 additions and 59 deletions

View File

@ -14,13 +14,13 @@ services:
steps: steps:
- name: verify - name: verify
image: python:3.13-alpine image: maven:3.9.11-eclipse-temurin-21-alpine
environment: environment:
ATLAS_LOCAL_PASSWORD: atlas-ci-example ATLAS_LOCAL_PASSWORD: atlas-ci-example
ATLAS_DELIVERY_PASSWORD: atlas-ci-delivery-example ATLAS_DELIVERY_PASSWORD: atlas-ci-delivery-example
commands: commands:
- sed -i 's|dl-cdn.alpinelinux.org/alpine|mirrors.aliyun.com/alpine|' /etc/apk/repositories - sed -i 's|dl-cdn.alpinelinux.org/alpine|mirrors.aliyun.com/alpine|' /etc/apk/repositories
- apk add --no-cache openjdk21-jdk maven postgresql-client - apk add --no-cache python3 postgresql-client
- mvn -B -ntp -f backend/pom.xml verify - mvn -B -ntp -f backend/pom.xml verify
- sh deploy/local/ci-smoke.sh - sh deploy/local/ci-smoke.sh
trigger: trigger:
@ -109,6 +109,7 @@ steps:
image: alpine/helm:3.20.0 image: alpine/helm:3.20.0
environment: environment:
HELM_DRIVER: configmap HELM_DRIVER: configmap
ATLAS_OTLP_TRACES_ENDPOINT: http://atlas-alloy.item-atlas-observability.svc:4318/v1/traces
ATLAS_KUBECONFIG_B64: ATLAS_KUBECONFIG_B64:
from_secret: atlas_staging_kubeconfig_b64 from_secret: atlas_staging_kubeconfig_b64
commands: commands:

View File

@ -32,3 +32,9 @@ Compose 的 `local` profile 带 `owner`、`viewer`、`other` 三个演示用户
本地模型接入 Ollama。云端提供方当前返回待配置。正式环境的账户开通、附件、云模型额度和完整接口契约后续接入。 本地模型接入 Ollama。云端提供方当前返回待配置。正式环境的账户开通、附件、云模型额度和完整接口契约后续接入。
[系统架构](../docs/architecture/system.md) · [部署和回退](../docs/deployment/backend-release.md) · [Maven 标准目录](https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html) [系统架构](../docs/architecture/system.md) · [部署和回退](../docs/deployment/backend-release.md) · [Maven 标准目录](https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html)
## 验收与排错
- 家庭建档使用 `POST /api/households`,请求体为 `{"name":"家庭名称"}`。创建者在同一事务成为 OWNER。用返回的 `Location` 查询家庭详情。
- 录入状态进入 `NEEDS_REVIEW` 后,草稿创建者可调用 `POST /api/households/{household}/operations/{operation}/retry`。返回 `202` 时继续查询同一操作号。当前操作最多支持启动一次额外恢复窗口。
- 业务覆盖、受限的功能和实际复现命令见 [后端验收](../docs/testing/backend-readiness.md) 与 [部署和监控](../docs/deployment/observability.md)。

View File

@ -13,6 +13,8 @@
<dependencies> <dependencies>
<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway-server-webflux</artifactId></dependency> <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway-server-webflux</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
<dependency><groupId>io.micrometer</groupId><artifactId>micrometer-registry-prometheus</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-opentelemetry</artifactId></dependency>
</dependencies> </dependencies>
<build> <build>
<finalName>app</finalName> <finalName>app</finalName>

View File

@ -24,7 +24,30 @@ spring:
- RequestSize=64KB - RequestSize=64KB
server: server:
port: ${PORT:8080} port: ${PORT:8080}
logging:
structured:
format:
console: ${ATLAS_LOG_FORMAT:logstash}
management: management:
metrics:
tags:
application: ${spring.application.name}
distribution:
percentiles-histogram:
http.server.requests: true
tracing:
propagation:
type: w3c
sampling:
probability: ${ATLAS_TRACE_SAMPLE_RATE:0.1}
export:
otlp:
enabled: ${ATLAS_OTLP_TRACES_ENABLED:false}
opentelemetry:
tracing:
export:
otlp:
endpoint: ${ATLAS_OTLP_TRACES_ENDPOINT:http://127.0.0.1:4318/v1/traces}
endpoint: endpoint:
health: health:
probes: probes:
@ -35,4 +58,4 @@ management:
endpoints: endpoints:
web: web:
exposure: exposure:
include: health,info include: health,info,prometheus

View File

@ -18,6 +18,8 @@
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-flyway</artifactId></dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-flyway</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
<dependency><groupId>io.micrometer</groupId><artifactId>micrometer-registry-prometheus</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-opentelemetry</artifactId></dependency>
<dependency><groupId>org.flywaydb</groupId><artifactId>flyway-database-postgresql</artifactId><scope>runtime</scope></dependency> <dependency><groupId>org.flywaydb</groupId><artifactId>flyway-database-postgresql</artifactId><scope>runtime</scope></dependency>
<dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><scope>runtime</scope></dependency> <dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><scope>runtime</scope></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-restclient</artifactId></dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-restclient</artifactId></dependency>

View File

@ -4,6 +4,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer; import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
@ -44,6 +45,7 @@ class ApiSecurity {
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(request -> request .authorizeHttpRequests(request -> request
.requestMatchers("/actuator/health/**").permitAll() .requestMatchers("/actuator/health/**").permitAll()
.requestMatchers(HttpMethod.GET, "/actuator/prometheus").permitAll()
.requestMatchers("/api/**").authenticated() .requestMatchers("/api/**").authenticated()
.anyRequest().denyAll()); .anyRequest().denyAll());
} }

View File

@ -3,7 +3,12 @@ package com.tutudog.itematlas.intake;
import static com.tutudog.itematlas.intake.IntakeDtos.*; import static com.tutudog.itematlas.intake.IntakeDtos.*;
import static org.springframework.http.HttpStatus.*; import static org.springframework.http.HttpStatus.*;
import io.micrometer.tracing.Tracer;
import io.micrometer.tracing.propagation.Propagator;
import java.sql.Types;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.UUID; import java.util.UUID;
import org.springframework.jdbc.core.simple.JdbcClient; import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -17,11 +22,15 @@ class DraftService {
private final JdbcClient db; private final JdbcClient db;
private final JsonMapper json; private final JsonMapper json;
private final DraftModel model; private final DraftModel model;
private final Tracer tracer;
private final Propagator propagator;
DraftService(JdbcClient db, JsonMapper json, DraftModel model) { DraftService(JdbcClient db, JsonMapper json, DraftModel model, Tracer tracer, Propagator propagator) {
this.db = db; this.db = db;
this.json = json; this.json = json;
this.model = model; this.model = model;
this.tracer = tracer;
this.propagator = propagator;
} }
Draft create(UUID household, String actor, String text) { Draft create(UUID household, String actor, String text) {
@ -70,14 +79,24 @@ class DraftService {
UUID operation = UUID.randomUUID(); UUID operation = UUID.randomUUID();
var payload = new Delivery(household, actor, input.items()); var payload = new Delivery(household, actor, input.items());
db.sql(""" db.sql("""
INSERT INTO confirm_operation(id,draft_id,draft_version,payload) INSERT INTO confirm_operation(id,draft_id,draft_version,payload,trace_parent)
VALUES (:operation,:id,:version,cast(:payload AS jsonb)) VALUES (:operation,:id,:version,cast(:payload AS jsonb),:traceParent)
""").param("operation", operation).param("id", id).param("version", input.version()) """).param("operation", operation).param("id", id).param("version", input.version())
.param("payload", json.writeValueAsString(payload)).update(); .param("payload", json.writeValueAsString(payload))
.param("traceParent", traceParent(), Types.VARCHAR).update();
db.sql("UPDATE draft SET status='PROCESSING' WHERE id=:id").param("id", id).update(); db.sql("UPDATE draft SET status='PROCESSING' WHERE id=:id").param("id", id).update();
return new Operation(operation, "PROCESSING"); return new Operation(operation, "PROCESSING");
} }
private String traceParent() {
var span = tracer.currentSpan();
if (span == null) { return null; }
Map<String, String> headers = new HashMap<>();
propagator.inject(span.context(), headers, Map::put);
// Persist just trace context. Request headers and baggage can contain private data.
return headers.get("traceparent");
}
Operation operation(UUID household, String actor, UUID operation) { Operation operation(UUID household, String actor, UUID operation) {
return db.sql(""" return db.sql("""
SELECT o.id,o.status FROM confirm_operation o JOIN draft d ON d.id=o.draft_id SELECT o.id,o.status FROM confirm_operation o JOIN draft d ON d.id=o.draft_id
@ -86,4 +105,18 @@ class DraftService {
.query((rs, row) -> new Operation(rs.getObject(1, UUID.class), rs.getString(2))).optional() .query((rs, row) -> new Operation(rs.getObject(1, UUID.class), rs.getString(2))).optional()
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "操作不存在")); .orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "操作不存在"));
} }
@Transactional
Operation retryOperation(UUID household, String actor, UUID operation) {
operation(household, actor, operation);
// Keep both the operation ID and the attempt counter so old workers cannot finish a new claim.
var draft = db.sql("""
UPDATE confirm_operation SET status='PROCESSING',attempt_limit=10,available_at=now(),lease_until=NULL
WHERE id=:id AND status='NEEDS_REVIEW' AND attempt_limit=5
RETURNING draft_id
""").param("id", operation).query(UUID.class).optional()
.orElseThrow(() -> new ResponseStatusException(CONFLICT, "当前操作无法再次重试"));
db.sql("UPDATE draft SET status='PROCESSING' WHERE id=:id").param("id", draft).update();
return new Operation(operation, "PROCESSING");
}
} }

View File

@ -58,6 +58,14 @@ class IntakeController {
return drafts.operation(household, principal.getName(), id); return drafts.operation(household, principal.getName(), id);
} }
@PostMapping(FAMILY + "/operations/{id}/retry")
ResponseEntity<Operation> retry(@PathVariable UUID household, @PathVariable UUID id, Principal principal,
@RequestHeader(HttpHeaders.AUTHORIZATION) String auth) {
inventory.checkAccess(household, auth, true);
var operation = drafts.retryOperation(household, principal.getName(), id);
return ResponseEntity.accepted().location(url(household, "operations", id)).body(operation);
}
private static URI url(UUID household, String type, UUID id) { private static URI url(UUID household, String type, UUID id) {
return URI.create("/api/households/" + household + "/" + type + "/" + id); return URI.create("/api/households/" + household + "/" + type + "/" + id);
} }

View File

@ -2,8 +2,15 @@ package com.tutudog.itematlas.intake;
import static com.tutudog.itematlas.intake.IntakeDtos.*; import static com.tutudog.itematlas.intake.IntakeDtos.*;
import io.micrometer.core.instrument.Gauge;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.tracing.Tracer;
import io.micrometer.tracing.propagation.Propagator;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.simple.JdbcClient; import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.scheduling.annotation.Scheduled; import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
@ -21,21 +28,26 @@ class Outbox {
Optional<Task> claim() { Optional<Task> claim() {
var expired = db.sql(""" var expired = db.sql("""
UPDATE confirm_operation SET status='NEEDS_REVIEW' UPDATE confirm_operation SET status='NEEDS_REVIEW'
WHERE status='PROCESSING' AND attempts >= 5 AND lease_until < now() RETURNING draft_id WHERE status='PROCESSING' AND attempts >= attempt_limit AND lease_until < now() RETURNING draft_id
""").query(UUID.class).list(); """).query(UUID.class).list();
for (UUID id : expired) { updateDraft(id, "NEEDS_REVIEW", false); } for (UUID id : expired) { updateDraft(id, "NEEDS_REVIEW", false); }
return db.sql(""" return db.sql("""
WITH next_task AS ( WITH next_task AS (
SELECT id FROM confirm_operation SELECT id FROM confirm_operation
WHERE status='PROCESSING' AND attempts < 5 AND available_at <= now() WHERE status='PROCESSING' AND attempts < attempt_limit AND available_at <= now()
AND (lease_until IS NULL OR lease_until <= now()) AND (lease_until IS NULL OR lease_until <= now())
ORDER BY available_at,id FOR UPDATE SKIP LOCKED LIMIT 1 ORDER BY available_at,id FOR UPDATE SKIP LOCKED LIMIT 1
) )
UPDATE confirm_operation o SET attempts=attempts+1,lease_until=now()+interval '30 seconds' UPDATE confirm_operation o SET attempts=attempts+1,lease_until=now()+interval '30 seconds'
FROM next_task WHERE o.id=next_task.id FROM next_task WHERE o.id=next_task.id
RETURNING o.id,o.draft_id,o.attempts,o.payload RETURNING o.id,o.draft_id,o.attempts,o.attempt_limit,o.payload,o.trace_parent
""").query((rs, row) -> new Task(rs.getObject(1, UUID.class), rs.getObject(2, UUID.class), rs.getInt(3), """).query((rs, row) -> new Task(rs.getObject(1, UUID.class), rs.getObject(2, UUID.class), rs.getInt(3),
json.readValue(rs.getString(4), Delivery.class))).optional(); rs.getInt(4), json.readValue(rs.getString(5), Delivery.class), rs.getString(6))).optional();
}
long count(String status) {
return db.sql("SELECT count(*) FROM confirm_operation WHERE status=:status")
.param("status", status).query(Long.class).single();
} }
@Transactional @Transactional
@ -49,13 +61,14 @@ class Outbox {
@Transactional @Transactional
void retry(Task task) { void retry(Task task) {
if (task.attempt() >= 5) { if (task.attempt() >= task.attemptLimit()) {
if (finish(task, "NEEDS_REVIEW") == 1) { updateDraft(task.draft(), "NEEDS_REVIEW", false); } if (finish(task, "NEEDS_REVIEW") == 1) { updateDraft(task.draft(), "NEEDS_REVIEW", false); }
} else { } else {
db.sql(""" db.sql("""
UPDATE confirm_operation SET available_at=now()+(:delay * interval '1 second'),lease_until=NULL UPDATE confirm_operation SET available_at=now()+(:delay * interval '1 second'),lease_until=NULL
WHERE id=:id AND attempts=:attempt AND status='PROCESSING' WHERE id=:id AND attempts=:attempt AND status='PROCESSING'
""").param("delay", 1 << task.attempt()).param("id", task.id()).param("attempt", task.attempt()).update(); """).param("delay", 1 << Math.min(task.attempt(), 4))
.param("id", task.id()).param("attempt", task.attempt()).update();
} }
} }
@ -71,29 +84,59 @@ class Outbox {
.param("status", status).param("delta", nextVersion ? 1 : 0).param("id", draft).update(); .param("status", status).param("delta", nextVersion ? 1 : 0).param("id", draft).update();
} }
record Task(UUID id, UUID draft, int attempt, Delivery payload) {} record Task(UUID id, UUID draft, int attempt, int attemptLimit, Delivery payload, String traceParent) {}
} }
@Component @Component
class OutboxWorker { class OutboxWorker {
private static final org.slf4j.Logger LOG = org.slf4j.LoggerFactory.getLogger(OutboxWorker.class); private static final Logger LOG = LoggerFactory.getLogger(OutboxWorker.class);
private final Outbox outbox; private final Outbox outbox;
private final InventoryClient inventory; private final InventoryClient inventory;
private final Tracer tracer;
private final Propagator propagator;
private final MeterRegistry meters;
OutboxWorker(Outbox outbox, InventoryClient inventory) { this.outbox = outbox; this.inventory = inventory; } OutboxWorker(Outbox outbox, InventoryClient inventory, Tracer tracer, Propagator propagator, MeterRegistry meters) {
this.outbox = outbox;
this.inventory = inventory;
this.tracer = tracer;
this.propagator = propagator;
this.meters = meters;
Gauge.builder("atlas.outbox.operations", outbox, source -> source.count("PROCESSING"))
.tag("state", "processing").register(meters);
Gauge.builder("atlas.outbox.operations", outbox, source -> source.count("NEEDS_REVIEW"))
.tag("state", "needs_review").register(meters);
}
@Scheduled(fixedDelayString = "${atlas.outbox.poll-ms:1000}") @Scheduled(fixedDelayString = "${atlas.outbox.poll-ms:1000}")
void deliver() { void deliver() {
outbox.claim().ifPresent(task -> { outbox.claim().ifPresent(this::deliverTask);
}
private void deliverTask(Outbox.Task task) {
var builder = task.traceParent() == null ? tracer.spanBuilder().setNoParent()
: propagator.extract(Map.of("traceparent", task.traceParent()), Map::get);
var span = builder.name("atlas.outbox.delivery").start()
.tag("atlas.operation.id", task.id().toString());
try (var scope = tracer.withSpan(span)) {
try { try {
DeliveryResult result = inventory.deliver(task.id(), task.payload()); DeliveryResult result = inventory.deliver(task.id(), task.payload());
if (result == null) { throw new IllegalStateException("Empty result"); } if (result == null) { throw new IllegalStateException("Empty result"); }
outbox.complete(task, result.outcome()); outbox.complete(task, result.outcome());
String outcome = "APPLIED".equals(result.outcome()) ? "applied" : "rejected";
span.tag("atlas.delivery.outcome", outcome);
meters.counter("atlas.outbox.delivery.attempts", "outcome", outcome).increment();
LOG.atInfo().addKeyValue("operationId", task.id()).addKeyValue("attempt", task.attempt())
.addKeyValue("outcome", outcome).log("Outbox delivery finished");
} catch (RuntimeException ex) { } catch (RuntimeException ex) {
LOG.warn("Delivery retry operation={} attempt={} error={}", span.tag("error.type", ex.getClass().getSimpleName());
task.id(), task.attempt(), ex.getClass().getSimpleName()); meters.counter("atlas.outbox.delivery.attempts", "outcome", "failed").increment();
LOG.atWarn().addKeyValue("operationId", task.id()).addKeyValue("attempt", task.attempt())
.addKeyValue("errorType", ex.getClass().getSimpleName()).log("Outbox delivery attempt failed");
outbox.retry(task); outbox.retry(task);
} }
}); } finally {
span.end();
}
} }
} }

View File

@ -28,7 +28,30 @@ server:
atlas: atlas:
inventory: inventory:
url: ${ATLAS_INVENTORY_URL:http://127.0.0.1:8081} url: ${ATLAS_INVENTORY_URL:http://127.0.0.1:8081}
logging:
structured:
format:
console: ${ATLAS_LOG_FORMAT:logstash}
management: management:
metrics:
tags:
application: ${spring.application.name}
distribution:
percentiles-histogram:
http.server.requests: true
tracing:
propagation:
type: w3c
sampling:
probability: ${ATLAS_TRACE_SAMPLE_RATE:0.1}
export:
otlp:
enabled: ${ATLAS_OTLP_TRACES_ENABLED:false}
opentelemetry:
tracing:
export:
otlp:
endpoint: ${ATLAS_OTLP_TRACES_ENDPOINT:http://127.0.0.1:4318/v1/traces}
endpoint: endpoint:
health: health:
probes: probes:
@ -39,4 +62,4 @@ management:
endpoints: endpoints:
web: web:
exposure: exposure:
include: health,info include: health,info,prometheus

View File

@ -0,0 +1,3 @@
ALTER TABLE confirm_operation
ADD COLUMN attempt_limit integer NOT NULL DEFAULT 5 CHECK (attempt_limit IN (5, 10)),
ADD COLUMN trace_parent text;

View File

@ -18,6 +18,8 @@
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-flyway</artifactId></dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-flyway</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency>
<dependency><groupId>io.micrometer</groupId><artifactId>micrometer-registry-prometheus</artifactId></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-opentelemetry</artifactId></dependency>
<dependency><groupId>org.flywaydb</groupId><artifactId>flyway-database-postgresql</artifactId><scope>runtime</scope></dependency> <dependency><groupId>org.flywaydb</groupId><artifactId>flyway-database-postgresql</artifactId><scope>runtime</scope></dependency>
<dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><scope>runtime</scope></dependency> <dependency><groupId>org.postgresql</groupId><artifactId>postgresql</artifactId><scope>runtime</scope></dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency> <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>

View File

@ -4,6 +4,10 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile; import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpMethod;
import org.springframework.security.authorization.AuthenticatedAuthorizationManager;
import org.springframework.security.authorization.AuthorizationManagers;
import org.springframework.security.authorization.AuthorityAuthorizationManager;
import org.springframework.security.config.Customizer; import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
@ -46,8 +50,12 @@ class ApiSecurity {
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(request -> request .authorizeHttpRequests(request -> request
.requestMatchers("/actuator/health/**").permitAll() .requestMatchers("/actuator/health/**").permitAll()
.requestMatchers(HttpMethod.GET, "/actuator/prometheus").permitAll()
.requestMatchers("/internal/**").hasAnyAuthority("SCOPE_atlas.deliver", "ROLE_DELIVERY") .requestMatchers("/internal/**").hasAnyAuthority("SCOPE_atlas.deliver", "ROLE_DELIVERY")
.requestMatchers("/api/**").authenticated() .requestMatchers("/api/**").access(AuthorizationManagers.allOf(
AuthenticatedAuthorizationManager.authenticated(),
AuthorizationManagers.not(
AuthorityAuthorizationManager.hasAnyAuthority("SCOPE_atlas.deliver", "ROLE_DELIVERY"))))
.anyRequest().denyAll()); .anyRequest().denyAll());
} }
} }

View File

@ -23,6 +23,17 @@ class InventoryController {
@GetMapping("/api/households") @GetMapping("/api/households")
List<Household> households(Principal user) { return service.households(user.getName()); } List<Household> households(Principal user) { return service.households(user.getName()); }
@PostMapping("/api/households")
ResponseEntity<Household> createHousehold(Principal user, @RequestBody @Valid HouseholdInput input) {
var household = service.createHousehold(user.getName(), input);
return ResponseEntity.created(URI.create("/api/households/" + household.id())).body(household);
}
@GetMapping(FAMILY)
Household getHousehold(@PathVariable UUID household, Principal user) {
return service.household(household, user.getName());
}
@GetMapping(FAMILY + "/locations") @GetMapping(FAMILY + "/locations")
List<Location> locations(@PathVariable UUID household, Principal user) { List<Location> locations(@PathVariable UUID household, Principal user) {
return service.locations(household, user.getName()); return service.locations(household, user.getName());
@ -37,9 +48,7 @@ class InventoryController {
@GetMapping(FAMILY + "/locations/{id}") @GetMapping(FAMILY + "/locations/{id}")
Location getLocation(@PathVariable UUID household, @PathVariable UUID id, Principal user) { Location getLocation(@PathVariable UUID household, @PathVariable UUID id, Principal user) {
return service.locations(household, user.getName()).stream().filter(location -> location.id().equals(id)) return service.location(household, user.getName(), id);
.findFirst().orElseThrow(() -> new org.springframework.web.server.ResponseStatusException(
org.springframework.http.HttpStatus.NOT_FOUND, "位置不存在"));
} }
@PutMapping(FAMILY + "/locations/{id}") @PutMapping(FAMILY + "/locations/{id}")
@ -97,6 +106,13 @@ class InventoryController {
return ResponseEntity.noContent().build(); return ResponseEntity.noContent().build();
} }
@DeleteMapping(FAMILY + "/items/{id}/relations/{related}")
ResponseEntity<Void> unlink(@PathVariable UUID household, @PathVariable UUID id,
@PathVariable UUID related, Principal user) {
service.unlink(household, user.getName(), id, related);
return ResponseEntity.noContent().build();
}
@PutMapping(FAMILY + "/items/{id}/preference") @PutMapping(FAMILY + "/items/{id}/preference")
Preference preference(@PathVariable UUID household, @PathVariable UUID id, Principal user, Preference preference(@PathVariable UUID household, @PathVariable UUID id, Principal user,
@Valid @RequestBody Preference input) { @Valid @RequestBody Preference input) {

View File

@ -13,6 +13,7 @@ import java.util.UUID;
final class InventoryDtos { final class InventoryDtos {
record Household(UUID id, String name, String role) {} record Household(UUID id, String name, String role) {}
record HouseholdInput(@NotBlank @Size(max = 100) String name) {}
record Location(UUID id, UUID parentId, String name, String path) {} record Location(UUID id, UUID parentId, String name, String path) {}
record LocationInput(@NotBlank @Size(max = 100) String name, UUID parentId) {} record LocationInput(@NotBlank @Size(max = 100) String name, UUID parentId) {}
record Item(UUID id, String name, int quantity, String notes, UUID locationId, record Item(UUID id, String name, int quantity, String notes, UUID locationId,

View File

@ -42,6 +42,26 @@ class InventoryService {
rs.getObject("id", UUID.class), rs.getString("name"), rs.getString("role"))).list(); rs.getObject("id", UUID.class), rs.getString("name"), rs.getString("role"))).list();
} }
Household household(UUID id, String actor) {
return db.sql("""
SELECT h.name,m.role FROM household h JOIN household_member m ON m.household_id=h.id
WHERE h.id=:id AND m.subject=:actor
""").param("id", id).param("actor", actor)
.query((rs, row) -> new Household(id, rs.getString(1), rs.getString(2))).optional()
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "家庭不存在"));
}
@Transactional
Household createHousehold(String actor, HouseholdInput input) {
UUID id = UUID.randomUUID();
String name = input.name().strip();
db.sql("INSERT INTO household(id,name) VALUES (:id,:name)")
.param("id", id).param("name", name).update();
db.sql("INSERT INTO household_member(household_id,subject,role) VALUES (:id,:actor,'OWNER')")
.param("id", id).param("actor", actor).update();
return new Household(id, name, "OWNER");
}
String role(UUID household, String actor) { String role(UUID household, String actor) {
return db.sql("SELECT role FROM household_member WHERE household_id=:id AND subject=:actor") return db.sql("SELECT role FROM household_member WHERE household_id=:id AND subject=:actor")
.param("id", household).param("actor", actor).query(String.class).optional() .param("id", household).param("actor", actor).query(String.class).optional()
@ -49,10 +69,15 @@ class InventoryService {
} }
private void requireWrite(UUID household, String actor) { private void requireWrite(UUID household, String actor) {
if ("VIEWER".equals(role(household, actor))) { // Serialize writes within a household so a move cannot race an archive or a tree change.
String membership = db.sql("""
SELECT m.role FROM household h JOIN household_member m ON m.household_id=h.id
WHERE h.id=:id AND m.subject=:actor FOR UPDATE OF h,m
""").param("id", household).param("actor", actor).query(String.class).optional()
.orElseThrow(() -> new ResponseStatusException(NOT_FOUND, "家庭不存在"));
if ("VIEWER".equals(membership)) {
throw new ResponseStatusException(FORBIDDEN, "当前角色只有查看权限"); throw new ResponseStatusException(FORBIDDEN, "当前角色只有查看权限");
} }
db.sql("SELECT id FROM household WHERE id=:id FOR UPDATE").param("id", household).query(UUID.class).single();
} }
List<Location> locations(UUID household, String actor) { List<Location> locations(UUID household, String actor) {
@ -61,6 +86,11 @@ class InventoryService {
.param("household", household).query(LOCATION).list(); .param("household", household).query(LOCATION).list();
} }
Location location(UUID household, String actor, UUID id) {
role(household, actor);
return location(household, id);
}
private Location location(UUID household, UUID id) { private Location location(UUID household, UUID id) {
return db.sql("SELECT * FROM location_path WHERE household_id=:household AND id=:id") return db.sql("SELECT * FROM location_path WHERE household_id=:household AND id=:id")
.param("household", household).param("id", id).query(LOCATION).optional() .param("household", household).param("id", id).query(LOCATION).optional()
@ -231,6 +261,14 @@ class InventoryService {
.param("kind", input.kind().name()).update(); .param("kind", input.kind().name()).update();
} }
@Transactional
void unlink(UUID household, String actor, UUID id, UUID related) {
requireWrite(household, actor);
item(household, id);
db.sql("DELETE FROM item_relation WHERE household_id=:household AND item_id=:id AND related_id=:related")
.param("household", household).param("id", id).param("related", related).update();
}
@Transactional @Transactional
Preference preference(UUID household, String actor, UUID id, Preference preference) { Preference preference(UUID household, String actor, UUID id, Preference preference) {
role(household, actor); role(household, actor);

View File

@ -10,7 +10,30 @@ spring:
enabled: true enabled: true
server: server:
port: ${PORT:8081} port: ${PORT:8081}
logging:
structured:
format:
console: ${ATLAS_LOG_FORMAT:logstash}
management: management:
metrics:
tags:
application: ${spring.application.name}
distribution:
percentiles-histogram:
http.server.requests: true
tracing:
propagation:
type: w3c
sampling:
probability: ${ATLAS_TRACE_SAMPLE_RATE:0.1}
export:
otlp:
enabled: ${ATLAS_OTLP_TRACES_ENABLED:false}
opentelemetry:
tracing:
export:
otlp:
endpoint: ${ATLAS_OTLP_TRACES_ENDPOINT:http://127.0.0.1:4318/v1/traces}
endpoint: endpoint:
health: health:
probes: probes:
@ -21,4 +44,4 @@ management:
endpoints: endpoints:
web: web:
exposure: exposure:
include: health,info include: health,info,prometheus

View File

@ -3,6 +3,7 @@ import base64
import concurrent.futures import concurrent.futures
import json import json
import os import os
import subprocess
import time import time
import uuid import uuid
from urllib.error import HTTPError, URLError from urllib.error import HTTPError, URLError
@ -20,7 +21,7 @@ OTHER_HOUSE = "/api/households/00000000-0000-0000-0000-000000000002"
RUN = uuid.uuid4().hex[:8] RUN = uuid.uuid4().hex[:8]
def call(method, path, payload=None, *, user="owner", status=200): def make_request(method, path, payload, user):
data = json.dumps(payload).encode() if payload is not None else None data = json.dumps(payload).encode() if payload is not None else None
request = Request(BASE + path, data=data, method=method) request = Request(BASE + path, data=data, method=method)
if data is not None: if data is not None:
@ -31,6 +32,11 @@ def call(method, path, payload=None, *, user="owner", status=200):
else: else:
token = base64.b64encode(f"{user}:{PASSWORD}".encode()).decode() token = base64.b64encode(f"{user}:{PASSWORD}".encode()).decode()
request.add_header("Authorization", f"Basic {token}") request.add_header("Authorization", f"Basic {token}")
return request
def call(method, path, payload=None, *, user="owner", status=200):
request = make_request(method, path, payload, user)
try: try:
response = urlopen(request, timeout=78) response = urlopen(request, timeout=78)
except HTTPError as error: except HTTPError as error:
@ -48,7 +54,7 @@ def ready():
call("GET", "/api/households") call("GET", "/api/households")
call("GET", "/api/model-providers") call("GET", "/api/model-providers")
return return
except (URLError, AssertionError): except (ConnectionError, URLError, AssertionError):
time.sleep(2) time.sleep(2)
raise AssertionError("Gateway and services did not become ready") raise AssertionError("Gateway and services did not become ready")
@ -57,19 +63,97 @@ def location(name, parent=None):
return call("POST", HOUSE + "/locations", {"name": name, "parentId": parent}, status=201)["id"] return call("POST", HOUSE + "/locations", {"name": name, "parentId": parent}, status=201)["id"]
def await_operation(path, expected):
for _ in range(30):
operation = call("GET", path)
if operation["status"] == expected:
return operation
time.sleep(0.5)
raise AssertionError(f"Expected operation state {expected}, got {operation}")
def recover_unacknowledged_delivery(dsn, operation, draft_path, name):
operation_id = str(uuid.UUID(operation["id"]))
path = f"{HOUSE}/operations/{operation_id}"
# Simulate losing the final acknowledgement after the inventory transaction committed.
# The test database is disposable and the item and inventory's deduplication result stay intact.
changed = subprocess.run(
["psql", dsn, "-XAt", "-v", "ON_ERROR_STOP=1"], text=True, capture_output=True, check=True,
input=f"""
WITH lost_ack AS (
UPDATE confirm_operation SET status='PROCESSING', attempts=5,
lease_until=now()-interval '1 second'
WHERE id='{operation_id}' AND status='COMPLETED'
RETURNING draft_id
)
UPDATE draft SET status='PROCESSING' WHERE id IN (SELECT draft_id FROM lost_ack);
""",
)
assert "UPDATE 1" in changed.stdout, changed.stdout
await_operation(path, "NEEDS_REVIEW")
assert call("GET", draft_path)["status"] == "NEEDS_REVIEW"
call("POST", path + "/retry", user="viewer", status=403)
call("POST", path + "/retry", user="other", status=404)
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
def retry_once():
try:
with urlopen(make_request("POST", path + "/retry", None, "owner"), timeout=10) as response:
return response.status, json.load(response)
except HTTPError as error:
return error.code, None
attempts = list(pool.map(lambda _: retry_once(), range(2)))
assert sorted(result[0] for result in attempts) == [202, 409], attempts
assert next(result[1] for result in attempts if result[0] == 202)["id"] == operation_id
await_operation(path, "COMPLETED")
assert call("GET", draft_path)["status"] == "COMPLETED"
call("POST", path + "/retry", status=409)
found = call("GET", HOUSE + "/items?" + urlencode({"q": name}))
assert len(found) == 1 and found[0]["name"] == name
print("PASS exhausted lease, one concurrent recovery and no duplicate after lost acknowledgement", flush=True)
def verify_metrics(targets):
outbox_seen = False
for target in targets.split(","):
with urlopen(target.rstrip("/") + "/actuator/prometheus", timeout=10) as response:
metrics = response.read().decode()
assert "http_server_requests_seconds_bucket" in metrics, target
outbox_seen |= "atlas_outbox_operations" in metrics and "atlas_outbox_delivery_attempts_total" in metrics
assert outbox_seen
print("PASS Prometheus metrics on gateway, inventory and intake", flush=True)
def main(): def main():
ready() ready()
call("GET", HOUSE + "/items", user=None, status=401) call("GET", HOUSE + "/items", user=None, status=401)
call("GET", HOUSE + "/items", user="other", status=404) call("GET", HOUSE + "/items", user="other", status=404)
call("GET", "/internal/operations/" + str(uuid.uuid4()), status=404) call("GET", "/internal/operations/" + str(uuid.uuid4()), status=404)
assert len(call("GET", "/api/households", user="viewer")) == 1 assert len(call("GET", "/api/households", user="viewer")) == 1
assert [row["id"] for row in call("GET", "/api/households", user="other")] == [OTHER_HOUSE.rsplit("/", 1)[1]] other_households = {row["id"] for row in call("GET", "/api/households", user="other")}
assert OTHER_HOUSE.rsplit("/", 1)[1] in other_households and HOUSE.rsplit("/", 1)[1] not in other_households
call("POST", "/api/households", {"name": "未登录"}, user=None, status=401)
call("POST", "/api/households", {"name": " "}, status=400)
created = call("POST", "/api/households", {"name": "刚创建 " + RUN}, user="other", status=201)
family_path = "/api/households/" + created["id"]
assert created["role"] == "OWNER" and call("GET", family_path, user="other") == created
call("GET", family_path, status=404)
delivery_password = os.environ.get("ATLAS_DELIVERY_PASSWORD") if not any(TOKENS.values()) else None
if delivery_password:
request = make_request("POST", "/api/households", {"name": "服务账号"}, None)
machine = base64.b64encode(f"atlas-delivery:{delivery_password}".encode()).decode()
request.add_header("Authorization", f"Basic {machine}")
try:
with urlopen(request, timeout=10) as response:
raise AssertionError(f"Delivery account unexpectedly received HTTP {response.status}")
except HTTPError as error:
assert error.code == 403, error.code
print("PASS authentication, household isolation and internal route boundary", flush=True) print("PASS authentication, household isolation and internal route boundary", flush=True)
study = location("书房 " + RUN) study = location("书房 " + RUN)
entry = location("玄关 " + RUN) entry = location("玄关 " + RUN)
box_a = location("白盒", study) box_a = location("白盒", study)
box_b = location("白盒", entry) box_b = location("白盒", entry)
assert call("GET", f"{HOUSE}/locations/{box_b}")["path"].startswith("玄关 ")
call("PUT", f"{HOUSE}/locations/{study}", {"name": "书房", "parentId": box_a}, status=409) call("PUT", f"{HOUSE}/locations/{study}", {"name": "书房", "parentId": box_a}, status=409)
call("DELETE", f"{HOUSE}/locations/{study}", status=409) call("DELETE", f"{HOUSE}/locations/{study}", status=409)
call("POST", HOUSE + "/locations", {"name": "不能新建"}, user="viewer", status=403) call("POST", HOUSE + "/locations", {"name": "不能新建"}, user="viewer", status=403)
@ -78,6 +162,9 @@ def main():
}, status=201) }, status=201)
found = call("GET", HOUSE + "/items?" + urlencode({"q": "视频线 " + RUN})) found = call("GET", HOUSE + "/items?" + urlencode({"q": "视频线 " + RUN}))
assert found[0]["id"] == item["id"] and found[0]["locationPath"].startswith("书房 ") assert found[0]["id"] == item["id"] and found[0]["locationPath"].startswith("书房 ")
by_path = call("GET", HOUSE + "/items?" + urlencode({"q": "书房 " + RUN}))
assert item["id"] in [row["id"] for row in by_path]
call("DELETE", f"{HOUSE}/locations/{box_a}", status=409)
item_path = f"{HOUSE}/items/{item['id']}" item_path = f"{HOUSE}/items/{item['id']}"
updated = call("POST", item_path + "/moves", {"locationId": box_b, "version": 0}) updated = call("POST", item_path + "/moves", {"locationId": box_b, "version": 0})
assert updated["version"] == 1 and updated["locationPath"].startswith("玄关 ") assert updated["version"] == 1 and updated["locationPath"].startswith("玄关 ")
@ -94,6 +181,12 @@ def main():
assert len(detail["moves"]) == 1 and detail["relations"][0]["itemId"] == related["id"] assert len(detail["moves"]) == 1 and detail["relations"][0]["itemId"] == related["id"]
assert detail["preference"]["rating"] == 5 assert detail["preference"]["rating"] == 5
assert call("GET", item_path, user="viewer")["preference"]["rating"] == 2 assert call("GET", item_path, user="viewer")["preference"]["rating"] == 2
call("PUT", item_path + "/preference", {"favorite": False, "rating": None, "note": ""}, user="viewer")
assert call("GET", item_path, user="viewer")["preference"] == {"favorite": False, "rating": None, "note": ""}
assert call("GET", item_path)["preference"]["rating"] == 5
call("DELETE", f"{item_path}/relations/{related['id']}", user="viewer", status=403)
call("DELETE", f"{item_path}/relations/{related['id']}", status=204)
assert call("GET", item_path)["relations"] == []
call("DELETE", f"{HOUSE}/items/{related['id']}?version=0", status=204) call("DELETE", f"{HOUSE}/items/{related['id']}?version=0", status=204)
call("GET", f"{HOUSE}/items/{related['id']}", status=404) call("GET", f"{HOUSE}/items/{related['id']}", status=404)
print("PASS location tree, alias search, optimistic version, history, related item and preferences", flush=True) print("PASS location tree, alias search, optimistic version, history, related item and preferences", flush=True)
@ -115,17 +208,17 @@ def main():
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
operations = list(pool.map(lambda _: call("POST", draft_path + "/confirm", payload, status=202), range(2))) operations = list(pool.map(lambda _: call("POST", draft_path + "/confirm", payload, status=202), range(2)))
assert operations[0]["id"] == operations[1]["id"], operations assert operations[0]["id"] == operations[1]["id"], operations
for _ in range(20): operation = await_operation(f"{HOUSE}/operations/{operations[0]['id']}", "COMPLETED")
operation = call("GET", f"{HOUSE}/operations/{operations[0]['id']}")
if operation["status"] == "COMPLETED":
break
time.sleep(0.5)
assert operation["status"] == "COMPLETED", operation
found = call("GET", HOUSE + "/items?" + urlencode({"q": name})) found = call("GET", HOUSE + "/items?" + urlencode({"q": name}))
assert len(found) == 1 and found[0]["name"] == name assert len(found) == 1 and found[0]["name"] == name
assert call("GET", draft_path)["status"] == "COMPLETED" assert call("GET", draft_path)["status"] == "COMPLETED"
print("PASS original text, model status, concurrent confirmation and single delivery", flush=True) print("PASS original text, model status, concurrent confirmation and single delivery", flush=True)
if dsn := os.environ.get("ATLAS_SMOKE_INTAKE_DSN"):
recover_unacknowledged_delivery(dsn, operation, draft_path, name)
if targets := os.environ.get("ATLAS_SMOKE_METRIC_TARGETS"):
verify_metrics(targets)
if __name__ == "__main__": if __name__ == "__main__":
main() main()

View File

@ -3,9 +3,9 @@
| 路径 | 用途 | | 路径 | 用途 |
| --- | --- | | --- | --- |
| `local/` | 本地联调和演示所需的 Compose 配置、样例环境变量 | | `local/` | 本地联调和演示所需的 Compose 配置、样例环境变量 |
| `helm/item-atlas/` | Kubernetes Helm Chart,部署网关、业务服务和 Web 镜像 | | `helm/item-atlas/` | Kubernetes Helm Chart,部署网关、物品与录入服务 |
| `nginx/` | 公网入口的 Nginx 配置模板,包含 Host 匹配和转发规则 | | `observability/` | 预发布 Prometheus、Grafana、Alloy、Loki 和 Tempo 的 Helm 配置与安装脚本 |
目录内放部署时能直接使用的文件。单个服务或 Web 应用的 Dockerfile 随源码维护。Drone 流水线文件随应用交付放在仓库根目录。提交的配置使用示例值,运行凭证从部署环境注入。 目录内放部署时能直接使用的文件。单个服务或 Web 应用的 Dockerfile 随源码维护。Drone 流水线文件随应用交付放在仓库根目录。提交的配置使用示例值,运行凭证从部署环境注入。
[部署架构](../docs/deployment/overview.md) · [后端交付与回退](../docs/deployment/backend-release.md) [部署架构](../docs/deployment/overview.md) · [后端交付与回退](../docs/deployment/backend-release.md) · [监控部署](../docs/deployment/observability.md)

View File

@ -60,6 +60,14 @@ spec:
value: {{ $workload.port | quote }} value: {{ $workload.port | quote }}
- name: JAVA_TOOL_OPTIONS - name: JAVA_TOOL_OPTIONS
value: "-XX:MaxRAMPercentage=65.0" value: "-XX:MaxRAMPercentage=65.0"
- name: ATLAS_TRACE_SAMPLE_RATE
value: {{ $root.Values.observability.traceSampleRate | quote }}
{{- with $root.Values.observability.otlpTracesEndpoint }}
- name: ATLAS_OTLP_TRACES_ENABLED
value: "true"
- name: ATLAS_OTLP_TRACES_ENDPOINT
value: {{ . | quote }}
{{- end }}
{{- if ne $workload.image "gateway" }} {{- if ne $workload.image "gateway" }}
- name: SPRING_PROFILES_ACTIVE - name: SPRING_PROFILES_ACTIVE
value: {{ $root.Values.profile | quote }} value: {{ $root.Values.profile | quote }}

View File

@ -6,6 +6,9 @@ imagePullSecrets: []
profile: release profile: release
inventorySecret: item-atlas-inventory inventorySecret: item-atlas-inventory
intakeSecret: item-atlas-intake intakeSecret: item-atlas-intake
observability:
otlpTracesEndpoint: ""
traceSampleRate: 0.1
canary: canary:
enabled: false enabled: false
tag: "" tag: ""

View File

@ -12,7 +12,11 @@ printf '%s' "$ATLAS_KUBECONFIG_B64" | base64 -d > "$atlas_kubeconfig"
unset ATLAS_KUBECONFIG_B64 unset ATLAS_KUBECONFIG_B64
export KUBECONFIG="$atlas_kubeconfig" export KUBECONFIG="$atlas_kubeconfig"
helm upgrade --install item-atlas deploy/helm/item-atlas --namespace "$namespace" \ set -- helm upgrade --install item-atlas deploy/helm/item-atlas --namespace "$namespace" \
--atomic --wait --timeout 12m --history-max 10 \ --atomic --wait --timeout 12m --history-max 10 \
--set-string "image.tag=$DRONE_COMMIT_SHA" \ --set-string "image.tag=$DRONE_COMMIT_SHA" \
--set 'imagePullSecrets[0].name=item-atlas-registry' --set 'imagePullSecrets[0].name=item-atlas-registry'
if [ -n "${ATLAS_OTLP_TRACES_ENDPOINT:-}" ]; then
set -- "$@" --set-string "observability.otlpTracesEndpoint=$ATLAS_OTLP_TRACES_ENDPOINT"
fi
"$@"

View File

@ -25,6 +25,8 @@ service_pids="$service_pids $!"
java -jar backend/gateway/target/app.jar > /tmp/atlas-gateway.log 2>&1 & java -jar backend/gateway/target/app.jar > /tmp/atlas-gateway.log 2>&1 &
service_pids="$service_pids $!" service_pids="$service_pids $!"
export ATLAS_SMOKE_INTAKE_DSN="postgresql://postgres@postgres/itematlas_intake"
export ATLAS_SMOKE_METRIC_TARGETS="http://127.0.0.1:8080,http://127.0.0.1:8081,http://127.0.0.1:8082"
if ! python3 backend/tests/smoke.py; then if ! python3 backend/tests/smoke.py; then
tail -80 /tmp/atlas-inventory.log /tmp/atlas-intake.log /tmp/atlas-gateway.log tail -80 /tmp/atlas-inventory.log /tmp/atlas-intake.log /tmp/atlas-gateway.log
exit 1 exit 1

View File

@ -0,0 +1,21 @@
fullnameOverride: atlas-alloy
rbac:
create: false
serviceAccount:
create: false
name: atlas-alloy
controller:
type: deployment
alloy:
extraPorts:
- name: otlp-http
port: 4318
targetPort: 4318
protocol: TCP
resources:
requests: {cpu: 50m, memory: 96Mi}
limits: {memory: 256Mi}
configReloader:
resources:
requests: {cpu: 10m, memory: 24Mi}
limits: {memory: 64Mi}

View File

@ -0,0 +1,64 @@
discovery.kubernetes "atlas_apps" {
role = "pod"
namespaces {
names = ["item-atlas-staging"]
}
selectors {
role = "pod"
label = "app.kubernetes.io/instance=item-atlas"
}
}
discovery.relabel "atlas_logs" {
targets = discovery.kubernetes.atlas_apps.targets
rule {
source_labels = ["__meta_kubernetes_pod_container_name"]
regex = "app"
action = "keep"
}
rule {
source_labels = ["__meta_kubernetes_namespace"]
target_label = "namespace"
}
rule {
source_labels = ["__meta_kubernetes_pod_label_app_kubernetes_io_name"]
target_label = "app"
}
rule {
source_labels = ["__meta_kubernetes_pod_name"]
target_label = "pod"
}
}
loki.source.kubernetes "atlas_logs" {
targets = discovery.relabel.atlas_logs.output
forward_to = [loki.write.atlas.receiver]
}
loki.write "atlas" {
endpoint {
url = "http://atlas-loki:3100/loki/api/v1/push"
}
}
otelcol.receiver.otlp "atlas" {
http {
endpoint = "0.0.0.0:4318"
}
output {
traces = [otelcol.processor.batch.atlas.input]
}
}
otelcol.processor.batch "atlas" {
output {
traces = [otelcol.exporter.otlphttp.tempo.input]
}
}
otelcol.exporter.otlphttp "tempo" {
client {
endpoint = "http://atlas-tempo:4318"
}
}

View File

@ -0,0 +1,43 @@
fullnameOverride: atlas-grafana
rbac:
create: false
serviceAccount:
automountServiceAccountToken: false
testFramework:
enabled: false
deploymentStrategy:
type: Recreate
persistence:
enabled: true
size: 1Gi
admin:
existingSecret: atlas-grafana-admin
resources:
requests: {cpu: 50m, memory: 128Mi}
limits: {memory: 384Mi}
datasources:
datasources.yaml:
apiVersion: 1
datasources:
- name: Prometheus
type: prometheus
uid: atlas-prometheus
access: proxy
url: http://atlas-prometheus-server:80
isDefault: true
- name: Loki
type: loki
uid: atlas-loki
access: proxy
url: http://atlas-loki:3100
jsonData:
derivedFields:
- name: TraceID
matcherRegex: '"traceId"\s*:\s*"([0-9a-f]+)"'
datasourceUid: atlas-tempo
url: '$${__value.raw}'
- name: Tempo
type: tempo
uid: atlas-tempo
access: proxy
url: http://atlas-tempo:3200

View File

@ -0,0 +1,37 @@
#!/bin/sh
set -eu
context=${1:?usage: deploy/observability/install.sh KUBERNETES_CONTEXT}
observability=item-atlas-observability
config_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
kubectl --context "$context" get namespace item-atlas-staging >/dev/null
kubectl --context "$context" -n "$observability" get secret atlas-grafana-admin -o name >/dev/null
kubectl --context "$context" apply --dry-run=server -f "$config_dir/serviceaccount.yaml" -f "$config_dir/rbac.yaml" >/dev/null
kubectl --context "$context" apply -f "$config_dir/serviceaccount.yaml" -f "$config_dir/rbac.yaml"
if [ -z "${ATLAS_CHART_DIR:-}" ]; then
helm repo add prometheus-community https://prometheus-community.github.io/helm-charts
helm repo add grafana-community https://grafana-community.github.io/helm-charts
helm repo add grafana https://grafana.github.io/helm-charts
helm repo update prometheus-community grafana-community grafana
fi
install_chart() {
component="$1"
chart="$2"
version="$3"
shift 3
if [ -n "${ATLAS_CHART_DIR:-}" ]; then
chart="$ATLAS_CHART_DIR/$component-$version.tgz"
fi
helm upgrade --install "atlas-$component" "$chart" --version "$version" \
--kube-context "$context" --namespace "$observability" --atomic --wait --timeout 8m \
-f "$config_dir/$component.yaml" "$@"
}
install_chart prometheus prometheus-community/prometheus 30.0.0
install_chart loki grafana-community/loki 21.6.0
install_chart tempo grafana-community/tempo 2.4.0
install_chart alloy grafana/alloy 1.16.0 --set-file "alloy.configMap.content=$config_dir/config.alloy"
install_chart grafana grafana-community/grafana 14.5.1

View File

@ -0,0 +1,53 @@
fullnameOverride: atlas-loki
deploymentMode: Monolithic
rbac:
namespaced: true
sidecar:
rules:
enabled: false
loki:
auth_enabled: false
commonConfig:
replication_factor: 1
storage:
type: filesystem
schemaConfig:
configs:
- from: "2024-04-01"
store: tsdb
object_store: filesystem
schema: v13
index:
prefix: index_
period: 24h
limits_config:
retention_period: 72h
compactor:
working_directory: /var/loki/compactor
retention_enabled: true
delete_request_store: filesystem
singleBinary:
replicas: 1
persistence:
size: 2Gi
whenDeleted: Retain
whenScaled: Retain
resources:
requests: {cpu: 75m, memory: 192Mi}
limits: {memory: 512Mi}
write:
replicas: 0
read:
replicas: 0
backend:
replicas: 0
gateway:
enabled: false
lokiCanary:
enabled: false
test:
enabled: false
chunksCache:
enabled: false
resultsCache:
enabled: false

View File

@ -0,0 +1,78 @@
fullnameOverride: atlas-prometheus
rbac:
create: false
serviceAccounts:
server:
name: atlas-prometheus
server:
retention: 3d
retentionSize: 1200MB
global:
scrape_interval: 30s
scrape_timeout: 5s
evaluation_interval: 30s
persistentVolume:
size: 2Gi
resources:
requests: {cpu: 75m, memory: 128Mi}
limits: {memory: 384Mi}
configmapReload:
prometheus:
resources:
requests: {cpu: 10m, memory: 24Mi}
limits: {memory: 64Mi}
alertmanager:
enabled: false
kube-state-metrics:
enabled: false
prometheus-node-exporter:
enabled: false
prometheus-pushgateway:
enabled: false
scrapeConfigs:
kubernetes-api-servers: {enabled: false}
kubernetes-nodes: {enabled: false}
kubernetes-nodes-cadvisor: {enabled: false}
kubernetes-service-endpoints: {enabled: false}
kubernetes-service-endpoints-slow: {enabled: false}
prometheus-pushgateway: {enabled: false}
kubernetes-services: {enabled: false}
kubernetes-pods: {enabled: false}
kubernetes-pods-slow: {enabled: false}
item-atlas:
metrics_path: /actuator/prometheus
kubernetes_sd_configs:
- role: pod
namespaces:
names: [item-atlas-staging]
selectors:
- role: pod
label: app.kubernetes.io/instance=item-atlas
relabel_configs:
- source_labels: [__meta_kubernetes_pod_phase]
action: keep
regex: Running
- source_labels: [__meta_kubernetes_pod_container_port_name]
action: keep
regex: http
- source_labels: [__meta_kubernetes_namespace]
target_label: namespace
- source_labels: [__meta_kubernetes_pod_name]
target_label: pod
- source_labels: [__meta_kubernetes_pod_label_app_kubernetes_io_name]
target_label: workload
serverFiles:
alerts:
groups:
- name: item-atlas
rules:
- alert: AtlasBackendScrapeDown
expr: up{job="item-atlas"} == 0
for: 2m
annotations:
summary: "无法采集 {{ $labels.workload }} 的应用指标"
- alert: AtlasOutboxNeedsReview
expr: max(atlas_outbox_operations{job="item-atlas",state="needs_review"}) > 0
for: 2m
annotations:
summary: "批量录入有待核查操作"

View File

@ -0,0 +1,50 @@
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: atlas-observability-discover
namespace: item-atlas-staging
rules:
- apiGroups: [""]
resources: [pods]
verbs: [get, list, watch]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: atlas-observability-discover
namespace: item-atlas-staging
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: atlas-observability-discover
subjects:
- kind: ServiceAccount
name: atlas-prometheus
namespace: item-atlas-observability
- kind: ServiceAccount
name: atlas-alloy
namespace: item-atlas-observability
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: atlas-observability-pod-logs
namespace: item-atlas-staging
rules:
- apiGroups: [""]
resources: [pods/log]
verbs: [get]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: atlas-observability-pod-logs
namespace: item-atlas-staging
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: atlas-observability-pod-logs
subjects:
- kind: ServiceAccount
name: atlas-alloy
namespace: item-atlas-observability

View File

@ -0,0 +1,5 @@
apiVersion: v1
kind: ServiceAccount
metadata:
name: atlas-alloy
namespace: item-atlas-observability

View File

@ -0,0 +1,11 @@
fullnameOverride: atlas-tempo
persistence:
enabled: true
size: 2Gi
tempo:
reportingEnabled: false
memBallastSizeMbs: 0
retention: 72h
resources:
requests: {cpu: 75m, memory: 192Mi}
limits: {memory: 384Mi}

View File

@ -4,6 +4,6 @@
| --- | --- | | --- | --- |
| 产品 | [调研](product/research.md)、[产品设计](product/overview.md)、[需求与验收](product/requirements.md) | | 产品 | [调研](product/research.md)、[产品设计](product/overview.md)、[需求与验收](product/requirements.md) |
| UI | [界面设计与走查](ui/README.md)、[低保真原型](ui/wireframes.md) | | UI | [界面设计与走查](ui/README.md)、[低保真原型](ui/wireframes.md) |
| 架构 | [系统架构](architecture/system.md)、[客户端选型](architecture/clients.md)、[模型接入](architecture/ai-providers.md)、[可观测性](architecture/observability.md) | | 架构 | [系统架构](architecture/system.md)、[客户端选型](architecture/clients.md)、[模型接入](architecture/ai-providers.md)、[可观测性](architecture/observability.md)、[两级缓存](architecture/cache.md) |
| 部署 | [部署架构、域名与发布](deployment/overview.md) | | 部署 | [部署架构、域名与发布](deployment/overview.md)、[预发布环境搭建](deployment/staging-bootstrap.md)、[监控安装](deployment/observability.md) |
| 测试 | [测试与演示计划](testing/plan.md)、[测试用例](testing/cases.md) | | 测试 | [测试与演示计划](testing/plan.md)、[测试用例](testing/cases.md)、[后端验收](testing/backend-readiness.md) |

View File

@ -0,0 +1,44 @@
# 两级缓存设计
当前业务以 PostgreSQL 为准。决定接入之前,用同一批数据测直查基线和热点分布。先选独立于权限、金额和写入幂等的只读数据,比较只用 Caffeine 和加入 Redis 后的收益。
| 方案 | 对项目的意义 |
| --- | --- |
| Spring Cache + Caffeine 或 Spring Data Redis | Spring 注解和自动配置,单层时够用。自动配置按条件选择一个 CacheManager,Caffeine 和 Redis 同时存在并不会组成 L1 → L2。 |
| Alibaba JetCache | 原生 `LOCAL`、`REMOTE`、`BOTH`,有编程式 Cache API、TTL、跨 JVM 失效和注解。新环境优先做 Boot 4.2、Redis 实例和序列化兼容性试验,再定版本。 |
| Redisson Spring Cache | 适合已有 Redisson 的项目。具体 Local Cache Manager 和失效功能按官方文档区分版本与许可。 |
[Spring Boot Cache](https://docs.spring.io/spring-boot/reference/io/caching.html) · [JetCache](https://github.com/alibaba/jetcache) · [JetCache 兼容表](https://github.com/alibaba/jetcache/blob/master/docs/CN/Compatibility.md) · [Redisson Spring Cache](https://redisson.pro/docs/cache/spring-cache/)
## 读写和故障边界
```mermaid
sequenceDiagram
participant A as 应用门面
participant C as Caffeine L1
participant R as Redis L2
participant D as 数据源
A->>C: 读 region + key
alt L1 缺失
A->>R: 读同一逻辑键
alt L2 缺失或超时
A->>D: 有界回源
D-->>A: 结果
A->>R: 按过期时间填充
end
A->>C: 按本地有效期填充
end
```
第一次接入可选模型状态探测,按 provider 和 model 分键。读取用户的家庭位置树时,先校验成员资格。需要读到刚保存的数据时,将家庭和位置版本纳入键,由 PostgreSQL 在树修改事务内递增版本,读取版本后再查对应投影。若没有实际热点,保持当前 SQL 直查。
- L1 有最大容量和短 TTL。L2 设置独立 TTL,L1 回填时限制有效期不超过 L2 的剩余有效期。数量、空值和异常的缓存策略按 region 声明。
- 写事务成功后删除 L2,再使各 JVM 的 L1 失效。滚回事务保留已有缓存。Redis Pub/Sub 是至多一次,重连时清理 L1、用短 TTL 限制残留。并发回填仍可能与失效交错,强需求使用版本键或持久事件及版本比较。
- Redis 超时按明确的时间预算降级。本机同键合并加载,回源用容量限制保护 PostgreSQL。记录 L1、L2 和回源的量级与失败,禁止把用户或键字段作为指标标签。
- 键至少包含应用、环境、region、schema 版本和租户。值用类型明确的 DTO JSON,滚动发布做版本兼容。成员授权、用户 token、额度、操作去重和草稿状态继续读取原业务数据源。
[Spring 事务后事件](https://docs.spring.io/spring-framework/reference/data-access/transaction/event.html) · [Redis Pub/Sub](https://redis.io/docs/latest/develop/pubsub/)
## 验证后再启用
用两个 JVM 和一个真实 Redis,分别测两级冷/热命中、同键并发、跨实例更新、失效过程中旧值回填、订阅断线、Redis 不可达、序列化版本变化和租户隔离。性能记录同时给无缓存、L1 和 L1+L2 的 P95、P99、回源 QPS、命中率、内存与失败比例。按实际收益和一致性要求选用。当前 Item Atlas 未部署 Redis,也未接入两级缓存。

View File

@ -8,13 +8,13 @@
| 信号 | 方案 | 首批观察指标 | | 信号 | 方案 | 首批观察指标 |
| --- | --- | --- | | --- | --- | --- |
| 指标 | Actuator、Micrometer、kubelet、kube-state-metrics → Prometheus → Grafana | 请求量、5xx、P95、Pod 重启、数据库连接、Outbox 积压、模型耗时和失败率 | | 指标 | Actuator、Micrometer → Prometheus → Grafana | 请求量、5xx、P95、数据库连接池、Outbox 积压 |
| 日志 | 应用输出 JSON 日志,Alloy 采集容器日志后写 Loki | 请求和操作编号、组件、版本、错误类型、`traceId` | | 日志 | 应用输出 JSON 日志,Alloy 采集容器日志后写 Loki | 请求和操作编号、组件、版本、错误类型、`traceId` |
| 链路 | Micrometer Tracing + OpenTelemetry,通过 Alloy 送到 Tempo | 网关、业务接口、数据库、模型和异步确认的耗时 | | 链路 | Micrometer Tracing + OpenTelemetry,通过 Alloy 送到 Tempo | 网关、业务接口、服务间请求和异步确认的耗时。逐条 SQL 耗时需再接 JDBC 观测。 |
公网 Nginx 记录请求编号并传给集群入口和网关。Java 服务传递 W3C `traceparent`。需要跨两层 Nginx 查入口故障时,用请求编号关联访问日志。Outbox 任务保存相应的追踪上下文和业务操作号。重试产生新的尝试记录,仍可通过操作号或 span link 回溯到原确认。日志和指标里只留必要的业务标识,原始草稿内容和 API 凭证由各自的数据路径处理。 [Spring Boot Tracing](https://docs.spring.io/spring-boot/reference/actuator/tracing.html) · [Alloy 采集与转发](https://grafana.com/docs/alloy/latest/collect/) 公网 Nginx 记录请求编号并传给集群入口和网关。Java 服务传递 W3C `traceparent`。需要跨两层 Nginx 查入口故障时,用请求编号关联访问日志。Outbox 任务保存相应的追踪上下文和业务操作号。重试产生新的尝试记录,仍可通过操作号或 span link 回溯到原确认。日志和指标里只留必要的业务标识,原始草稿内容和 API 凭证由各自的数据路径处理。 [Spring Boot Tracing](https://docs.spring.io/spring-boot/reference/actuator/tracing.html) · [Alloy 采集与转发](https://grafana.com/docs/alloy/latest/collect/)
Prometheus 和 Grafana 先接入服务及集群指标,随后补 Alloy、Loki 和 Tempo。演示环境用较短保留时间、本地 SSD 持久卷和单进程部署。看板通过受控入口访问。 [Loki 单实例存储](https://grafana.com/docs/loki/latest/setup/install/helm/configure-storage/) · [Tempo 小规模部署](https://grafana.com/docs/tempo/latest/set-up-for-tracing/setup-tempo/plan/) 预发布用 Prometheus 采集应用指标,Alloy 转发日志和链路,Loki 和 Tempo 各自使用单进程和 SSD 持久卷。当前采集范围是应用 Pod。kubelet、kube-state-metrics、数据库底层监控与告警通知需按环境另配。Grafana 走回环端口转发。 [安装和排错](../deployment/observability.md) · [Loki 单实例存储](https://grafana.com/docs/loki/latest/setup/install/helm/configure-storage/) · [Tempo 小规模部署](https://grafana.com/docs/tempo/latest/set-up-for-tracing/setup-tempo/plan/)
## 上线后怎么查 ## 上线后怎么查

View File

@ -10,15 +10,15 @@
| 服务 | 管什么 | 相关需求 | | 服务 | 管什么 | 相关需求 |
| --- | --- | --- | | --- | --- | --- |
| `gateway` | Spring Cloud Gateway 提供 API 路由、统一认证入口、限流和版本分流。 | R01 | | `gateway` | Spring Cloud Gateway 提供 API 路由、请求体大小限制和物品读请求的版本分流。 | R01 |
| `inventory-service` | 账号和家庭、物品、位置、移动历史、别名搜索、关联、收藏和个人评分。 | R01、R02、R03、R04、R05、R08 | | `inventory-service` | 家庭建档和成员权限、物品、位置、移动历史、别名搜索、关联、收藏和个人评分。 | R01、R02、R03、R04、R05、R08 |
| `intake-service` | 批量草稿、模型提供方、调用额度、录入任务和执行结果。 | R06、R07 | | `intake-service` | 批量草稿、模型提供方状态、本地模型、录入任务和执行结果。 | R06、R07 |
H5、PC 和管理后台是独立的 Web 入口。网关验证身份,业务服务校验家庭归属、角色和数据状态。跨服务的确认请求须带服务身份和原操作人,写入前由物品服务重新核对权限。 [客户端与后台](clients.md) H5、PC 和管理后台规划为独立 Web 入口。网关转发业务请求,两个服务分别验证 Token,并检查家庭归属、角色和数据状态。跨服务的确认请求须带服务身份和原操作人,写入前由物品服务重新核对权限。 [客户端与后台](clients.md)
## Spring Cloud 用在哪里 ## Spring Cloud 用在哪里
Spring Boot 负责服务本身,Spring Cloud 主要用 Gateway。域名和 TLS 在 Nginx,API 路径、限流和稳定版/候选版分流放网关。这样增加客户端和灰度规则时,两套业务服务的入口保持一致。服务名通过 Kubernetes Service 和 DNS 找到。配置从 Helm、ConfigMap 和 Secret 进入容器,首版按这个范围配置。 Spring Boot 负责服务本身,Spring Cloud 主要用 Gateway。正式部署将域名和 TLS 放在 Nginx,API 路径和稳定版/候选版分流放网关。这样增加客户端和灰度规则时,两套业务服务的入口保持一致。服务名通过 Kubernetes Service 和 DNS 找到。配置从 Helm 和 Secret 进入容器。
当前使用 Java 21、Spring Boot 4.2.0、Spring Cloud 2026.0.0、Spring AI 2.1.0 和 Maven。业务库用 PostgreSQL 和 Flyway,集成冒烟直接访问 PostgreSQL 和两个服务。接口约定逐步补齐 OpenAPI。 [Spring Boot 4.2](https://spring.io/blog/2026/11/19/spring-boot-4-2-0-available-now/) · [Spring Cloud 2026.0](https://spring.io/blog/2026/11/20/spring-cloud-2026-0-0-has-been-released/) · [Spring AI 2.1](https://spring.io/blog/2026/11/20/spring-ai-2-1-0-GA-available-now/) 当前使用 Java 21、Spring Boot 4.2.0、Spring Cloud 2026.0.0、Spring AI 2.1.0 和 Maven。业务库用 PostgreSQL 和 Flyway,集成冒烟直接访问 PostgreSQL 和两个服务。接口约定逐步补齐 OpenAPI。 [Spring Boot 4.2](https://spring.io/blog/2026/11/19/spring-boot-4-2-0-available-now/) · [Spring Cloud 2026.0](https://spring.io/blog/2026/11/20/spring-cloud-2026-0-0-has-been-released/) · [Spring AI 2.1](https://spring.io/blog/2026/11/20/spring-ai-2-1-0-GA-available-now/)
@ -26,7 +26,7 @@ Spring Boot 负责服务本身,Spring Cloud 主要用 Gateway。域名和 TLS
## 数据和接口 ## 数据和接口
首版共用一个 PostgreSQL 实例,按服务划分数据库和账号。物品、位置和偏好归物品服务,草稿、Outbox 和模型用量归录入服务。跨服务访问走接口。附件由物品服务统一校验归属。 首版共用一个 PostgreSQL 实例,按服务划分数据库和账号。物品、位置和偏好归物品服务,草稿和 Outbox 归录入服务。跨服务访问走接口。附件与云模型用量将在相应模块交付。
| 数据 | 校验 | | 数据 | 校验 |
| --- | --- | | --- | --- |
@ -35,7 +35,7 @@ Spring Boot 负责服务本身,Spring Cloud 主要用 Gateway。域名和 TLS
| 收藏和评分 | 按用户和物品唯一保存,用户可以改分、取消收藏或清除短评。 | | 收藏和评分 | 按用户和物品唯一保存,用户可以改分、取消收藏或清除短评。 |
| 草稿 | 保存输入、候选项和确认状态。同一草稿版本只接受一份确认任务。 | | 草稿 | 保存输入、候选项和确认状态。同一草稿版本只接受一份确认任务。 |
业务路径放在 `/api/households/{householdId}` 下。`/items`、`/locations`、`/items/{id}/moves` 和 `/items/{id}/preference` 走物品服务。`/drafts`、`/drafts/{id}/confirm` 和 `/operations/{id}` 走录入服务。模型状态走 `/api/model-providers`,后台管理用独立的 `/api/admin` 前缀。内部投递路径只允许服务访问。 业务路径放在 `/api/households/{householdId}` 下。`/items`、`/locations`、`/items/{id}/moves` 和 `/items/{id}/preference` 走物品服务。`/drafts`、`/drafts/{id}/confirm` 和 `/operations/{id}` 走录入服务。模型状态走 `/api/model-providers`,后台管理预留独立的 `/api/admin` 前缀。内部投递路径只允许服务访问。
## 草稿确认与分布式一致性 ## 草稿确认与分布式一致性
@ -44,14 +44,14 @@ Spring Boot 负责服务本身,Spring Cloud 主要用 Gateway。域名和 TLS
[原图](diagrams/draft-confirmation.png) · [Mermaid 源文件](diagrams/draft-confirmation.mmd) [原图](diagrams/draft-confirmation.png) · [Mermaid 源文件](diagrams/draft-confirmation.mmd)
1. 用户确认时,录入服务用本地事务把草稿改为处理中,并写一条 Outbox 任务。接口返回 `202` 和操作编号。 1. 用户确认时,录入服务用本地事务把草稿改为处理中,并写一条 Outbox 任务。接口返回 `202` 和操作编号。
2. 同一服务里的后台任务按批领取已提交的任务,带操作编号调用物品服务。物品服务按操作编号保存结果。成功时在一个本地事务里写物品、移位记录和幂等结果。 2. 同一服务里的后台 Worker 每次领取一条已提交的任务,带操作编号调用物品服务。物品服务按操作编号保存结果。成功时在一个本地事务里写物品和幂等结果。
3. 收到成功结果后更新草稿状态。如果物品已经写入但响应丢了,重试仍用同一编号,物品服务返回原结果。位置或权限变化导致明确拒绝时,物品服务按该编号保存拒绝结果,草稿恢复为待修正。重放仍返回同一结果。 3. 收到成功结果后更新草稿状态。如果物品已经写入但响应丢了,重试仍用同一编号,物品服务返回原结果。位置或权限变化导致明确拒绝时,物品服务按该编号保存拒绝结果,草稿恢复为待修正。重放仍返回同一结果。
4. 任务结果不明时保留处理中,超过重试预算后进入待核查。用户可以用操作编号查询。草稿版本和唯一约束分别处理并发确认、重复写入和重放。 4. 任务结果不明时保留处理中,超过重试预算后进入待核查。草稿创建者可查询并触发一次额外恢复,沿用原操作号和递增的尝试序号。草稿版本和唯一约束处理并发确认、重复写入和重放。
这里采用 Outbox 和幂等请求做最终一致性。数据库事务只覆盖各自服务的写入,模型调用和跨服务等待都在事务之外。确认后想撤销,按正常移位或归档规则处理。 这里采用 Outbox 和幂等请求做最终一致性。数据库事务只覆盖各自服务的写入,模型调用和跨服务等待都在事务之外。确认后想撤销,按正常移位或归档规则处理。
## 并发和容量 ## 并发和容量
普通搜索、手工录入与模型生成分开设超时。单机 Ollama 先按单并发推理,录入服务的任务队列有上限。云端先预留用户和项目额度,拿到实际用量再结算。投递按有限并发和退避重试控制积压,前端定期查状态。演示用两个家庭、并发确认、响应丢失和模型故障验证。吞吐和延迟以实测为准。 普通搜索、手工录入与模型生成分开设超时。录入服务每个实例保留一个本地模型调用槽,单机 Ollama 的推理容量需按实测配置。Worker 每次领取一条并退避重试,前端定期查状态。模型额度、队列容量告警和正式入口的速率限制分别跟踪。在容量测试后确定吞吐和延迟目标。
[需求与验收](../product/requirements.md) · [模型接入](ai-providers.md) · [部署与发布](../deployment/overview.md) · [测试与演示](../testing/plan.md) [需求与验收](../product/requirements.md) · [模型接入](ai-providers.md) · [两级缓存设计](cache.md) · [部署与发布](../deployment/overview.md) · [后端验收](../testing/backend-readiness.md)

View File

@ -0,0 +1,55 @@
# 预发布监控部署
应用、采集器和查询端都使用 Kubernetes 内部服务。预发布由五个独立的上游 Helm release 组成。Prometheus 拉指标,Alloy 从 Kubernetes API 读应用日志并接收 OTLP 链路,Grafana 统一查询。告警规则由 Prometheus 计算,当前在 Prometheus 页面查看。
| 组件 | Chart 版本 | 内网入口 | 存储 |
| --- | --- | --- | --- |
| Prometheus | `prometheus-community/prometheus@30.0.0` | `atlas-prometheus-server:80` | 2 GiB,保留 3 天,容量目标 1200 MB |
| Loki | `grafana-community/loki@21.6.0` | `atlas-loki:3100` | 2 GiB,单进程 TSDB 文件存储,保留 72 小时 |
| Tempo | `grafana-community/tempo@2.4.0` | 查询 `atlas-tempo:3200`,OTLP HTTP `atlas-tempo:4318` | 2 GiB,单进程本地块存储,保留 72 小时 |
| Alloy | `grafana/alloy@1.16.0` | OTLP HTTP `atlas-alloy:4318` | 收发缓冲 |
| Grafana | `grafana-community/grafana@14.5.1` | `atlas-grafana:80` | 1 GiB,数据源由 Helm 提供 |
Tempo 固定在 2.x 的单进程部署。升级到 3.x 前要单独核对消息队列、存储和迁移要求。现有预发布的开发型 StorageClass 由 SSD VM 提供,文件和 TSDB 的保留占用以实际磁盘监控为准。 [Prometheus Chart](https://github.com/prometheus-community/helm-charts/tree/main/charts/prometheus) · [Grafana Helm](https://grafana.com/docs/grafana/latest/setup-grafana/installation/helm/) · [Loki 单进程](https://grafana.com/docs/loki/latest/setup/install/helm/install-monolithic/) · [Tempo 部署](https://grafana.com/docs/tempo/latest/set-up-for-tracing/setup-tempo/deploy/) · [Alloy Helm](https://grafana.com/docs/alloy/latest/set-up/install/kubernetes/)
## 安装和更新
先核对工作集群、`item-atlas-staging` 命名空间、默认 StorageClass 和 SSD 余量。由集群维护账号创建监控命名空间,并在其下创建 `atlas-grafana-admin` Secret。将管理员密码以受控文件输入,执行后安全移除临时文件。
```sh
kubectl --context kind-atlas-dev create namespace item-atlas-observability
kubectl --context kind-atlas-dev -n item-atlas-observability create secret generic atlas-grafana-admin \
--from-literal=admin-user=admin --from-file=admin-password=/path/to/managed-password-file
sh deploy/observability/install.sh kind-atlas-dev
kubectl --context kind-atlas-dev -n item-atlas-observability get deployment,statefulset,pvc,service
```
安装脚本核对现有环境,用服务端 dry run 校验 Role、RoleBinding 和 ServiceAccount,再执行 Helm `--atomic --wait`。若环境只能从内网下载,先按脚本的版本将官方 Chart 下载为 `组件-版本.tgz`,通过 `ATLAS_CHART_DIR` 指定其目录。Prometheus 只需在预发布读 Pod,Alloy 另需读同一命名空间的 `pods/log`。应用遥测端点、数据查询端和 Collector 均使用 ClusterIP。上线环境应当在入口只转业务路径,并为采集和查询配置对应的网络权限。 [Kubernetes RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/)
## Java 接入的位置
1. 三个服务的 `pom.xml` 都引入 `spring-boot-starter-actuator`、`micrometer-registry-prometheus`、`spring-boot-starter-opentelemetry`,版本由 Spring Boot BOM 管。各自 `application.yml` 打开 Prometheus endpoint,启用 HTTP 延迟直方图并设置结构化日志。
2. HTTP 服务和从 Boot 注入的 `RestClient.Builder` 继承 Spring 的观测配置。用代码自行 new 出的 HTTP 客户端要单独检查透传和采集。配置 OTLP HTTP exporter 时,应用的 URL 带 `/v1/traces`。Alloy → Tempo 的 exporter 使用基础地址,由 exporter 拼接对应路径。
3. `DraftService.confirm` 在同一事务保存操作和 W3C `traceparent`。`OutboxWorker.deliverTask` 恢复父上下文,给每次尝试开一个 span,用结构化字段写操作号、尝试序号和结果。操作号和 trace ID 只用于日志与链路,指标标签使用有界的状态和结果。
4. `deploy/helm/item-atlas/values.yaml` 的 `observability.otlpTracesEndpoint` 为空时关闭 OTLP 导出。Drone 的预发布 Promotion 已传入 Alloy 地址,采样默认 10%。专项演练可通过 `observability.traceSampleRate` 设置采样,完成后恢复原值。 [Spring Boot 指标](https://docs.spring.io/spring-boot/reference/actuator/metrics.html) · [Spring Boot 链路](https://docs.spring.io/spring-boot/reference/actuator/tracing.html) · [结构化日志](https://docs.spring.io/spring-boot/reference/features/logging.html#features.logging.structured)
## 验收和排错
从有集群权限的终端做回环端口转发。下面各条命令分别运行,Grafana 使用安装时保存在 Secret 管理渠道的账号。
```sh
kubectl -n item-atlas-observability port-forward svc/atlas-grafana 3000:80
kubectl -n item-atlas-observability port-forward svc/atlas-prometheus-server 9090:80
kubectl -n item-atlas-observability port-forward svc/atlas-loki 3100:3100
kubectl -n item-atlas-observability port-forward svc/atlas-tempo 3200:3200
```
| 目的 | 查询和预期 |
| --- | --- |
| 确认采集 | Prometheus 查看 `up{job="item-atlas"}`,三个稳定工作负载正常时均为 1。若全无结果,依次查 Pod 标签、RBAC、目标发现与 endpoint。 |
| 查看 HTTP P95 | `histogram_quantile(0.95, sum by (le, workload) (rate(http_server_requests_seconds_bucket{job="item-atlas",uri!~"/actuator/.*"}[5m])))`,演练前先造一定真实业务流量。 |
| 查录入积压 | `max by (state) (atlas_outbox_operations{job="item-atlas"})`,同一数据库可能被多副本采集,取最大值。用 `increase(atlas_outbox_delivery_attempts_total[5m])` 看尝试结果。 |
| 查日志 | Grafana Explore 中使用 `{namespace="item-atlas-staging", app="item-atlas-intake-service"} | json | operationId = "操作号"`。 |
| 查链路 | 从上述日志的 TraceID 进入 Tempo。被采样的请求可沿网关到录入,再看到 `atlas.outbox.delivery` 到物品服务。还可用 `GET /api/traces/<traceId>` 验证 Tempo 已接收。 |
遇到日志、指标或链路缺一项,先检查该信号的写入端和中间组件。指标与日志时间窗以查询端为准。合成探针和短时间提采样适合演练。升级各 Chart 前记录 `helm history`,故障用 `helm rollback RELEASE REVISION -n item-atlas-observability --wait`,随后再查 Pod、PVC、数据源与代表请求。监控中断时,应用回退和数据库恢复按照 [后端交付和回退](backend-release.md) 单独处理。

View File

@ -4,6 +4,33 @@
[原图](diagrams/deployment.png) · [draw.io 源文件](diagrams/deployment.drawio) [原图](diagrams/deployment.png) · [draw.io 源文件](diagrams/deployment.drawio)
原图描述正式部署的目标。当前预发布由外置 SSD 上的 ARM64 Lima VM、kind 和内网端口转发承载。云端负责 Git、CI 与制品,工作机 runner 负责镜像和部署,家用 Mac 提供推理。
```mermaid
flowchart LR
subgraph Cloud["云端 CI"]
G["Gitea · OCI 仓库"]
D["Drone · AMD64 验证"]
G --> D
end
subgraph Work["工作 Mac · SSD · ARM64 Linux VM"]
R["Drone ARM64 runner"]
subgraph Cluster["kind · Kubernetes"]
A["网关 → 物品 / 录入"]
P["PostgreSQL / Keycloak"]
T["Prometheus / Alloy → Loki / Tempo → Grafana"]
A --> P
A --> T
end
R -->|Helm Promotion| A
end
D --> R
R -->|推送镜像| G
A -->|家庭内网| O["家用 Mac · Ollama"]
```
[预发布环境搭建](staging-bootstrap.md) · [监控部署](observability.md)
## 设备和网络 ## 设备和网络
| 位置 | 角色 | | 位置 | 角色 |

View File

@ -0,0 +1,39 @@
# 新建预发布环境
预发布可以运行在独立 kind 集群或现有 Kubernetes 的独立命名空间。现有运行环境是外置 SSD 上的 ARM64 Lima VM 和 kind。工作机与模型机使用家庭私网。建立新环境前确认 Kubernetes 节点架构、可用 StorageClass、DNS、各 HTTPS 服务证书和可用磁盘。使用本机盘时,先确认 SSD 挂载位置。 [kind 配置](https://kind.sigs.k8s.io/docs/user/configuration/) · [Kubernetes 存储类](https://kubernetes.io/docs/concepts/storage/storage-classes/)
## 运行依赖
| 依赖 | 初始化与检查 |
| --- | --- |
| PostgreSQL 17 | 用官方容器部署一个 StatefulSet 和内网 Service `atlas-postgres:5432`。独立持久卷挂载数据目录。初始化两个库和两个角色,应用角色保持库所有者权限以执行 Flyway。 |
| Keycloak 26.8.2 | 预发布可用官方容器启动 `start-dev`,用独立 PVC 保留测试数据,由 `atlas-keycloak:8080` 提供内网 OIDC。正式环境使用稳定模式、HTTPS 和正式数据库。 |
| Gitea 镜像仓库 | 给 Drone 单独安排可以推送镜像的包凭据。为当前 namespace 的 `item-atlas-registry` 使用另一组只读包凭据。 |
| Ollama | 可选。使用录入 Pod 可达的内网 URL,先检查 `/api/tags`,确认配置的模型名出现。禁用时走手工录入。 |
| 监控 | 应用依赖确认后运行 [监控安装](observability.md)。监控组件使用独立命名空间和存储,应用的发布身份只需要预发布应用权限。 |
PostgreSQL 初始化示例。在管理员 psql 会话执行,交互设置两个口令。现有环境重跑前先用 `\du`、`\l` 核对角色与库。 [PostgreSQL 官方镜像](https://hub.docker.com/_/postgres)
```sql
CREATE ROLE atlas_inventory LOGIN;
CREATE ROLE atlas_intake LOGIN;
\password atlas_inventory
\password atlas_intake
CREATE DATABASE itematlas_inventory OWNER atlas_inventory;
CREATE DATABASE itematlas_intake OWNER atlas_intake;
```
Keycloak 为预发布创建独立 realm `item-atlas-staging`。在客户端作用域内添加 audience mapper,目标为 `item-atlas-api`,并确保 access token 含 `sub`。原生验收客户端开放 Authorization Code + PKCE S256,只允许登记的回调;用测试账号确认 issuer、audience、subject。服务客户端 `atlas-intake` 开启客户端凭证,绑定同一 audience 与 `atlas.deliver` scope。从 Pod 内可以访问 issuer 的发现文档和 JWKS。使用临时端口转发做登录测试时,必须保持测试令牌的 issuer 与应用校验值一致。 [Keycloak 容器](https://www.keycloak.org/server/containers) · [Keycloak OIDC](https://www.keycloak.org/securing-apps/oidc-layers)
应用依赖通过 `item-atlas-inventory`、`item-atlas-intake` Secret 注入。字段全表见 [后端交付](backend-release.md)。连接 URL 选择相应数据库,OIDC issuer 用服务发现地址,录入客户端 token URL 用同一 realm 的 `/protocol/openid-connect/token`。密码、密钥、kubeconfig、数据库转储不提交到 Git。
## 发布和复核
1. 创建 `item-atlas-staging`,核对 PostgreSQL 与 Keycloak 的 Service、EndpointSlice、Pod 与 PVC。数据库权限按服务分隔,未确认身份和数据前先用独立样例。
2. 为 Drone 建预发布发布身份。限制在该 namespace,允许管理 Deployments、Services、ConfigMaps、Jobs,并读 Pod、ReplicaSet 和事件。Helm 的 release 流水用 ConfigMap 存修订,业务 Secret 由维护账号管理。让专用 ARM64 runner 用单独 kubeconfig 验证 `helm list`。
3. 发布构建并 Promotion 到 `staging`。确认 Flyway 版本、Pod Ready、接口就绪和摘要。新用户用已验证的 OIDC 身份创建家庭。家庭隔离验收继续使用专用样例账号和专用两户数据。
4. 正式环境在此基础上验证独立身份源、Ingress/Nginx 公网协议、frp 回环和网络权限。反向代理只转发已确认的业务路径,内部路由、Actuator 和监控不经过公网。需要发行版、信任范围和数据备份确认后再开公网。
## 备份与恢复
给业务库分别做 `pg_dump -Fc`,文件放权限受控的 SSD 备份目录。记录快照时间、应用版本、数据库和是否还有未完成的确认。完整备份需要协调两个库的一致截点,可在停写后执行。恢复时先建两套空库,用 `pg_restore --exit-on-error --no-owner` 恢复,然后核对表行数、角色、Flyway 历史和同一操作号,确认就绪再切换应用。Keycloak 数据与配置另做备份。SSD 单盘的本地备份用于误操作恢复,介质故障需准备另一份备份。 [pg_dump](https://www.postgresql.org/docs/current/app-pgdump.html) · [pg_restore](https://www.postgresql.org/docs/current/app-pgrestore.html)

View File

@ -0,0 +1,26 @@
# 后端验收清单
首版按照需求编号验收。发布前可从这张表找对应入口和测试。运行结果同时看 Drone、目标环境和业务响应。
| 需求 | 当前 API 和证据 | 后续边界 |
| --- | --- | --- |
| R01 家庭和角色 | 已登录的用户创建家庭后成为 OWNER,家庭详情和用户可访问的家庭列表受 JWT subject 约束。冒烟覆盖两个家庭、查看者、投递服务账号和匿名请求。 | 成员邀请、角色维护和管理后台 API 待交付。 |
| R02 多层位置 | 测试两处同名收纳盒、完整路径、位置详情、非法循环、存在子节点或物品时拒绝归档。 | 大位置树用真实容量样本分析 SQL。 |
| R03 物品和移位 | 新建、编辑、移位、归档和历史走真实 PostgreSQL。旧版本写入返回 409。 | 客户端需用刷新后的版本重新提交。 |
| R04 搜索 | 对同一物品用别名和完整位置路径搜索,响应保持完整路径。 | 按数据量评估搜索索引和分页,先保留原生 SQL 基线。 |
| R05 物品关联 | 保存同户关系和展示完整位置。新增删除关联,查看者不能执行。关联对象需按同一家庭查找。 | 自动相似推荐待交付。 |
| R06 批量草稿 | 本地 Ollama 验证数量、否定和不确定位置。并发确认只生成一个操作,实际写入一次。注入已写入但最后确认丢失场景后,同一操作号恢复并复核只写一次。 | 恢复次数有上限,需要人工处理持续失败。 |
| R07 模型状态 | 本地模型可用、未配置和手工确认路径。云端模型只提供待配置状态。 | 云端适配、选模及账本额度、并发扣费与用量对账待验收。 |
| R08 收藏与评分 | 两个用户分别评价同一物品,一方清除后,另一方评价保持。 | 客户端将评分清除表达为 `rating: null`。 |
附件服务与附件恢复单独验收。目前有数据库备份恢复的实测记录。公网登录、域名证书、网络隔离及上线后的告警通知在正式环境单列核对。
## 复现
- 构建用 `mvn -B -ntp -f backend/pom.xml verify`。
- CI 使用短生命周期 PostgreSQL 并执行 `deploy/local/ci-smoke.sh`。该脚本包含三个服务、真实数据库、模型缺省降级、重新投递和指标验收。
- 预发布用 Keycloak 签发的三个账号跑同一冒烟脚本,确认 OIDC、真实 Ollama、镜像摘要和应用日志。需要改数据库状态的故障注入在独立测试库运行。
- 两个服务的数据按各自 Flyway 迁移版本维护。`V2__confirm_retry_budget.sql` 给已有记录补默认重试限额,新记录存可选 trace parent。第一轮切入新接口前等待旧录入 Pod 完成更新。老版本可读新增列的数据库,但回退时先确认新增恢复任务不在处理中。
- 监控部署后查 Prometheus Targets 和 Outbox 指标,用操作号在 Loki 查日志,再看 Tempo 的对应 trace。详细步骤见 [监控部署](../deployment/observability.md)。
[需求与验收](../product/requirements.md) · [逐项测试用例](cases.md) · [交付和灰度](../deployment/backend-release.md)

View File

@ -1,6 +1,6 @@
# 首版测试用例 # 首版测试用例
以下是待执行用例。R01–R08 对应[需求与验收](../product/requirements.md)。 R01–R08 对应[需求与验收](../product/requirements.md)。实现和当前可执行范围见[后端验收清单](backend-readiness.md)。
| 用例 | 需求 | 准备与操作 | 预期结果 | | 用例 | 需求 | 准备与操作 | 预期结果 |
| --- | --- | --- | --- | | --- | --- | --- | --- |