diff --git a/.drone.yml b/.drone.yml
index b77872e..34181a1 100644
--- a/.drone.yml
+++ b/.drone.yml
@@ -14,13 +14,13 @@ services:
steps:
- name: verify
- image: python:3.13-alpine
+ image: maven:3.9.11-eclipse-temurin-21-alpine
environment:
ATLAS_LOCAL_PASSWORD: atlas-ci-example
ATLAS_DELIVERY_PASSWORD: atlas-ci-delivery-example
commands:
- 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
- sh deploy/local/ci-smoke.sh
trigger:
@@ -109,6 +109,7 @@ steps:
image: alpine/helm:3.20.0
environment:
HELM_DRIVER: configmap
+ ATLAS_OTLP_TRACES_ENDPOINT: http://atlas-alloy.item-atlas-observability.svc:4318/v1/traces
ATLAS_KUBECONFIG_B64:
from_secret: atlas_staging_kubeconfig_b64
commands:
diff --git a/backend/gateway/pom.xml b/backend/gateway/pom.xml
index ed8f1e4..cb6912e 100644
--- a/backend/gateway/pom.xml
+++ b/backend/gateway/pom.xml
@@ -13,6 +13,8 @@
org.springframework.cloudspring-cloud-starter-gateway-server-webflux
org.springframework.bootspring-boot-starter-actuator
+ io.micrometermicrometer-registry-prometheus
+ org.springframework.bootspring-boot-starter-opentelemetry
app
diff --git a/backend/gateway/src/main/resources/application.yml b/backend/gateway/src/main/resources/application.yml
index c875e34..9b8a300 100644
--- a/backend/gateway/src/main/resources/application.yml
+++ b/backend/gateway/src/main/resources/application.yml
@@ -24,7 +24,30 @@ spring:
- RequestSize=64KB
server:
port: ${PORT:8080}
+logging:
+ structured:
+ format:
+ console: ${ATLAS_LOG_FORMAT:logstash}
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:
health:
probes:
@@ -35,4 +58,4 @@ management:
endpoints:
web:
exposure:
- include: health,info
+ include: health,info,prometheus
diff --git a/backend/intake-service/pom.xml b/backend/intake-service/pom.xml
index 7bf9bd4..b82d6c1 100644
--- a/backend/intake-service/pom.xml
+++ b/backend/intake-service/pom.xml
@@ -18,6 +18,8 @@
org.springframework.bootspring-boot-starter-jdbc
org.springframework.bootspring-boot-starter-flyway
org.springframework.bootspring-boot-starter-actuator
+ io.micrometermicrometer-registry-prometheus
+ org.springframework.bootspring-boot-starter-opentelemetry
org.flywaydbflyway-database-postgresqlruntime
org.postgresqlpostgresqlruntime
org.springframework.bootspring-boot-starter-restclient
diff --git a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/ApiSecurity.java b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/ApiSecurity.java
index a08c133..e83ad20 100644
--- a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/ApiSecurity.java
+++ b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/ApiSecurity.java
@@ -4,6 +4,7 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
+import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
@@ -44,6 +45,7 @@ class ApiSecurity {
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(request -> request
.requestMatchers("/actuator/health/**").permitAll()
+ .requestMatchers(HttpMethod.GET, "/actuator/prometheus").permitAll()
.requestMatchers("/api/**").authenticated()
.anyRequest().denyAll());
}
diff --git a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/DraftService.java b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/DraftService.java
index 3e00f61..40fe9bc 100644
--- a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/DraftService.java
+++ b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/DraftService.java
@@ -3,7 +3,12 @@ package com.tutudog.itematlas.intake;
import static com.tutudog.itematlas.intake.IntakeDtos.*;
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.Map;
import java.util.UUID;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.stereotype.Service;
@@ -17,11 +22,15 @@ class DraftService {
private final JdbcClient db;
private final JsonMapper json;
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.json = json;
this.model = model;
+ this.tracer = tracer;
+ this.propagator = propagator;
}
Draft create(UUID household, String actor, String text) {
@@ -70,14 +79,24 @@ class DraftService {
UUID operation = UUID.randomUUID();
var payload = new Delivery(household, actor, input.items());
db.sql("""
- INSERT INTO confirm_operation(id,draft_id,draft_version,payload)
- VALUES (:operation,:id,:version,cast(:payload AS jsonb))
+ INSERT INTO confirm_operation(id,draft_id,draft_version,payload,trace_parent)
+ VALUES (:operation,:id,:version,cast(:payload AS jsonb),:traceParent)
""").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();
return new Operation(operation, "PROCESSING");
}
+ private String traceParent() {
+ var span = tracer.currentSpan();
+ if (span == null) { return null; }
+ Map 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) {
return db.sql("""
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()
.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");
+ }
}
diff --git a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/IntakeController.java b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/IntakeController.java
index 8761800..221dafa 100644
--- a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/IntakeController.java
+++ b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/IntakeController.java
@@ -58,6 +58,14 @@ class IntakeController {
return drafts.operation(household, principal.getName(), id);
}
+ @PostMapping(FAMILY + "/operations/{id}/retry")
+ ResponseEntity 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) {
return URI.create("/api/households/" + household + "/" + type + "/" + id);
}
diff --git a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/Outbox.java b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/Outbox.java
index e066807..d08b85b 100644
--- a/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/Outbox.java
+++ b/backend/intake-service/src/main/java/com/tutudog/itematlas/intake/Outbox.java
@@ -2,8 +2,15 @@ package com.tutudog.itematlas.intake;
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.UUID;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.simple.JdbcClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@@ -21,21 +28,26 @@ class Outbox {
Optional claim() {
var expired = db.sql("""
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();
for (UUID id : expired) { updateDraft(id, "NEEDS_REVIEW", false); }
return db.sql("""
WITH next_task AS (
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())
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'
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),
- 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
@@ -49,13 +61,14 @@ class Outbox {
@Transactional
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); }
} else {
db.sql("""
UPDATE confirm_operation SET available_at=now()+(:delay * interval '1 second'),lease_until=NULL
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();
}
- 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
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 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}")
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 {
DeliveryResult result = inventory.deliver(task.id(), task.payload());
if (result == null) { throw new IllegalStateException("Empty result"); }
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) {
- LOG.warn("Delivery retry operation={} attempt={} error={}",
- task.id(), task.attempt(), ex.getClass().getSimpleName());
+ span.tag("error.type", 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);
}
- });
+ } finally {
+ span.end();
+ }
}
}
diff --git a/backend/intake-service/src/main/resources/application.yml b/backend/intake-service/src/main/resources/application.yml
index 94b2cdb..191f26f 100644
--- a/backend/intake-service/src/main/resources/application.yml
+++ b/backend/intake-service/src/main/resources/application.yml
@@ -28,7 +28,30 @@ server:
atlas:
inventory:
url: ${ATLAS_INVENTORY_URL:http://127.0.0.1:8081}
+logging:
+ structured:
+ format:
+ console: ${ATLAS_LOG_FORMAT:logstash}
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:
health:
probes:
@@ -39,4 +62,4 @@ management:
endpoints:
web:
exposure:
- include: health,info
+ include: health,info,prometheus
diff --git a/backend/intake-service/src/main/resources/db/migration/V2__confirm_retry_budget.sql b/backend/intake-service/src/main/resources/db/migration/V2__confirm_retry_budget.sql
new file mode 100644
index 0000000..5ce040b
--- /dev/null
+++ b/backend/intake-service/src/main/resources/db/migration/V2__confirm_retry_budget.sql
@@ -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;
diff --git a/backend/inventory-service/pom.xml b/backend/inventory-service/pom.xml
index 9ae6d36..13c5c4c 100644
--- a/backend/inventory-service/pom.xml
+++ b/backend/inventory-service/pom.xml
@@ -18,6 +18,8 @@
org.springframework.bootspring-boot-starter-jdbc
org.springframework.bootspring-boot-starter-flyway
org.springframework.bootspring-boot-starter-actuator
+ io.micrometermicrometer-registry-prometheus
+ org.springframework.bootspring-boot-starter-opentelemetry
org.flywaydbflyway-database-postgresqlruntime
org.postgresqlpostgresqlruntime
org.springframework.bootspring-boot-starter-testtest
diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/ApiSecurity.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/ApiSecurity.java
index 946732b..d576554 100644
--- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/ApiSecurity.java
+++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/ApiSecurity.java
@@ -4,6 +4,10 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
@@ -46,8 +50,12 @@ class ApiSecurity {
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(request -> request
.requestMatchers("/actuator/health/**").permitAll()
+ .requestMatchers(HttpMethod.GET, "/actuator/prometheus").permitAll()
.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());
}
}
diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryController.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryController.java
index 67f6709..8306a0b 100644
--- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryController.java
+++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryController.java
@@ -23,6 +23,17 @@ class InventoryController {
@GetMapping("/api/households")
List households(Principal user) { return service.households(user.getName()); }
+ @PostMapping("/api/households")
+ ResponseEntity 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")
List locations(@PathVariable UUID household, Principal user) {
return service.locations(household, user.getName());
@@ -37,9 +48,7 @@ class InventoryController {
@GetMapping(FAMILY + "/locations/{id}")
Location getLocation(@PathVariable UUID household, @PathVariable UUID id, Principal user) {
- return service.locations(household, user.getName()).stream().filter(location -> location.id().equals(id))
- .findFirst().orElseThrow(() -> new org.springframework.web.server.ResponseStatusException(
- org.springframework.http.HttpStatus.NOT_FOUND, "位置不存在"));
+ return service.location(household, user.getName(), id);
}
@PutMapping(FAMILY + "/locations/{id}")
@@ -97,6 +106,13 @@ class InventoryController {
return ResponseEntity.noContent().build();
}
+ @DeleteMapping(FAMILY + "/items/{id}/relations/{related}")
+ ResponseEntity 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")
Preference preference(@PathVariable UUID household, @PathVariable UUID id, Principal user,
@Valid @RequestBody Preference input) {
diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryDtos.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryDtos.java
index 775c7d1..dfe45f9 100644
--- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryDtos.java
+++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryDtos.java
@@ -13,6 +13,7 @@ import java.util.UUID;
final class InventoryDtos {
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 LocationInput(@NotBlank @Size(max = 100) String name, UUID parentId) {}
record Item(UUID id, String name, int quantity, String notes, UUID locationId,
diff --git a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryService.java b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryService.java
index a422746..8d70edf 100644
--- a/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryService.java
+++ b/backend/inventory-service/src/main/java/com/tutudog/itematlas/inventory/InventoryService.java
@@ -42,6 +42,26 @@ class InventoryService {
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) {
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()
@@ -49,10 +69,15 @@ class InventoryService {
}
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, "当前角色只有查看权限");
}
- db.sql("SELECT id FROM household WHERE id=:id FOR UPDATE").param("id", household).query(UUID.class).single();
}
List locations(UUID household, String actor) {
@@ -61,6 +86,11 @@ class InventoryService {
.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) {
return db.sql("SELECT * FROM location_path WHERE household_id=:household AND id=:id")
.param("household", household).param("id", id).query(LOCATION).optional()
@@ -231,6 +261,14 @@ class InventoryService {
.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
Preference preference(UUID household, String actor, UUID id, Preference preference) {
role(household, actor);
diff --git a/backend/inventory-service/src/main/resources/application.yml b/backend/inventory-service/src/main/resources/application.yml
index 03ffb8c..0f20b80 100644
--- a/backend/inventory-service/src/main/resources/application.yml
+++ b/backend/inventory-service/src/main/resources/application.yml
@@ -10,7 +10,30 @@ spring:
enabled: true
server:
port: ${PORT:8081}
+logging:
+ structured:
+ format:
+ console: ${ATLAS_LOG_FORMAT:logstash}
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:
health:
probes:
@@ -21,4 +44,4 @@ management:
endpoints:
web:
exposure:
- include: health,info
+ include: health,info,prometheus
diff --git a/backend/tests/smoke.py b/backend/tests/smoke.py
index 3c6ba01..9982c2d 100644
--- a/backend/tests/smoke.py
+++ b/backend/tests/smoke.py
@@ -3,6 +3,7 @@ import base64
import concurrent.futures
import json
import os
+import subprocess
import time
import uuid
from urllib.error import HTTPError, URLError
@@ -20,7 +21,7 @@ OTHER_HOUSE = "/api/households/00000000-0000-0000-0000-000000000002"
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
request = Request(BASE + path, data=data, method=method)
if data is not None:
@@ -31,6 +32,11 @@ def call(method, path, payload=None, *, user="owner", status=200):
else:
token = base64.b64encode(f"{user}:{PASSWORD}".encode()).decode()
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:
response = urlopen(request, timeout=78)
except HTTPError as error:
@@ -48,7 +54,7 @@ def ready():
call("GET", "/api/households")
call("GET", "/api/model-providers")
return
- except (URLError, AssertionError):
+ except (ConnectionError, URLError, AssertionError):
time.sleep(2)
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"]
+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():
ready()
call("GET", HOUSE + "/items", user=None, status=401)
call("GET", HOUSE + "/items", user="other", status=404)
call("GET", "/internal/operations/" + str(uuid.uuid4()), status=404)
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)
study = location("书房 " + RUN)
entry = location("玄关 " + RUN)
box_a = location("白盒", study)
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("DELETE", f"{HOUSE}/locations/{study}", status=409)
call("POST", HOUSE + "/locations", {"name": "不能新建"}, user="viewer", status=403)
@@ -78,6 +162,9 @@ def main():
}, status=201)
found = call("GET", HOUSE + "/items?" + urlencode({"q": "视频线 " + RUN}))
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']}"
updated = call("POST", item_path + "/moves", {"locationId": box_b, "version": 0})
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 detail["preference"]["rating"] == 5
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("GET", f"{HOUSE}/items/{related['id']}", status=404)
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:
operations = list(pool.map(lambda _: call("POST", draft_path + "/confirm", payload, status=202), range(2)))
assert operations[0]["id"] == operations[1]["id"], operations
- for _ in range(20):
- operation = call("GET", f"{HOUSE}/operations/{operations[0]['id']}")
- if operation["status"] == "COMPLETED":
- break
- time.sleep(0.5)
- assert operation["status"] == "COMPLETED", operation
+ operation = await_operation(f"{HOUSE}/operations/{operations[0]['id']}", "COMPLETED")
found = call("GET", HOUSE + "/items?" + urlencode({"q": name}))
assert len(found) == 1 and found[0]["name"] == name
assert call("GET", draft_path)["status"] == "COMPLETED"
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__":
main()
diff --git a/deploy/helm/item-atlas/templates/workloads.yaml b/deploy/helm/item-atlas/templates/workloads.yaml
index 98742b8..ace221d 100644
--- a/deploy/helm/item-atlas/templates/workloads.yaml
+++ b/deploy/helm/item-atlas/templates/workloads.yaml
@@ -60,6 +60,14 @@ spec:
value: {{ $workload.port | quote }}
- name: JAVA_TOOL_OPTIONS
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" }}
- name: SPRING_PROFILES_ACTIVE
value: {{ $root.Values.profile | quote }}
diff --git a/deploy/helm/item-atlas/values.yaml b/deploy/helm/item-atlas/values.yaml
index 6b0ccf9..35d2af0 100644
--- a/deploy/helm/item-atlas/values.yaml
+++ b/deploy/helm/item-atlas/values.yaml
@@ -6,6 +6,9 @@ imagePullSecrets: []
profile: release
inventorySecret: item-atlas-inventory
intakeSecret: item-atlas-intake
+observability:
+ otlpTracesEndpoint: ""
+ traceSampleRate: 0.1
canary:
enabled: false
tag: ""
diff --git a/deploy/helm/promote.sh b/deploy/helm/promote.sh
index e2b7ecf..3f6ad2c 100755
--- a/deploy/helm/promote.sh
+++ b/deploy/helm/promote.sh
@@ -12,7 +12,11 @@ printf '%s' "$ATLAS_KUBECONFIG_B64" | base64 -d > "$atlas_kubeconfig"
unset ATLAS_KUBECONFIG_B64
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 \
--set-string "image.tag=$DRONE_COMMIT_SHA" \
--set 'imagePullSecrets[0].name=item-atlas-registry'
+if [ -n "${ATLAS_OTLP_TRACES_ENDPOINT:-}" ]; then
+ set -- "$@" --set-string "observability.otlpTracesEndpoint=$ATLAS_OTLP_TRACES_ENDPOINT"
+fi
+"$@"
diff --git a/deploy/local/ci-smoke.sh b/deploy/local/ci-smoke.sh
index 66d6cad..cf0fdcc 100755
--- a/deploy/local/ci-smoke.sh
+++ b/deploy/local/ci-smoke.sh
@@ -25,6 +25,8 @@ service_pids="$service_pids $!"
java -jar backend/gateway/target/app.jar > /tmp/atlas-gateway.log 2>&1 &
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
tail -80 /tmp/atlas-inventory.log /tmp/atlas-intake.log /tmp/atlas-gateway.log
exit 1
diff --git a/deploy/observability/alloy.yaml b/deploy/observability/alloy.yaml
new file mode 100644
index 0000000..4f9b0bb
--- /dev/null
+++ b/deploy/observability/alloy.yaml
@@ -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}
diff --git a/deploy/observability/config.alloy b/deploy/observability/config.alloy
new file mode 100644
index 0000000..04d747b
--- /dev/null
+++ b/deploy/observability/config.alloy
@@ -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"
+ }
+}
diff --git a/deploy/observability/grafana.yaml b/deploy/observability/grafana.yaml
new file mode 100644
index 0000000..5ba4119
--- /dev/null
+++ b/deploy/observability/grafana.yaml
@@ -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
diff --git a/deploy/observability/install.sh b/deploy/observability/install.sh
new file mode 100644
index 0000000..636789f
--- /dev/null
+++ b/deploy/observability/install.sh
@@ -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
diff --git a/deploy/observability/loki.yaml b/deploy/observability/loki.yaml
new file mode 100644
index 0000000..d164677
--- /dev/null
+++ b/deploy/observability/loki.yaml
@@ -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
diff --git a/deploy/observability/prometheus.yaml b/deploy/observability/prometheus.yaml
new file mode 100644
index 0000000..b5a0ca3
--- /dev/null
+++ b/deploy/observability/prometheus.yaml
@@ -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: "批量录入有待核查操作"
diff --git a/deploy/observability/rbac.yaml b/deploy/observability/rbac.yaml
new file mode 100644
index 0000000..65407f7
--- /dev/null
+++ b/deploy/observability/rbac.yaml
@@ -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
diff --git a/deploy/observability/serviceaccount.yaml b/deploy/observability/serviceaccount.yaml
new file mode 100644
index 0000000..1b2e767
--- /dev/null
+++ b/deploy/observability/serviceaccount.yaml
@@ -0,0 +1,5 @@
+apiVersion: v1
+kind: ServiceAccount
+metadata:
+ name: atlas-alloy
+ namespace: item-atlas-observability
diff --git a/deploy/observability/tempo.yaml b/deploy/observability/tempo.yaml
new file mode 100644
index 0000000..4642389
--- /dev/null
+++ b/deploy/observability/tempo.yaml
@@ -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}
diff --git a/docs/architecture/cache.md b/docs/architecture/cache.md
new file mode 100644
index 0000000..85b63f5
--- /dev/null
+++ b/docs/architecture/cache.md
@@ -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,也未接入两级缓存。
diff --git a/docs/deployment/observability.md b/docs/deployment/observability.md
new file mode 100644
index 0000000..6f745c6
--- /dev/null
+++ b/docs/deployment/observability.md
@@ -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/` 验证 Tempo 已接收。 |
+
+遇到日志、指标或链路缺一项,先检查该信号的写入端和中间组件。指标与日志时间窗以查询端为准。合成探针和短时间提采样适合演练。升级各 Chart 前记录 `helm history`,故障用 `helm rollback RELEASE REVISION -n item-atlas-observability --wait`,随后再查 Pod、PVC、数据源与代表请求。监控中断时,应用回退和数据库恢复按照 [后端交付和回退](backend-release.md) 单独处理。