feat: 补齐家庭建档、录入恢复和预发布监控
This commit is contained in:
parent
8de002c23b
commit
0dfb0b656b
|
|
@ -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:
|
||||||
|
|
|
||||||
|
|
@ -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>
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
|
|
||||||
|
|
@ -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>
|
||||||
|
|
|
||||||
|
|
@ -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());
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
|
|
||||||
|
|
@ -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;
|
||||||
|
|
@ -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>
|
||||||
|
|
|
||||||
|
|
@ -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());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -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) {
|
||||||
|
|
|
||||||
|
|
@ -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,
|
||||||
|
|
|
||||||
|
|
@ -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);
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
|
|
||||||
|
|
@ -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()
|
||||||
|
|
|
||||||
|
|
@ -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 }}
|
||||||
|
|
|
||||||
|
|
@ -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: ""
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
"$@"
|
||||||
|
|
|
||||||
|
|
@ -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
|
||||||
|
|
|
||||||
|
|
@ -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}
|
||||||
|
|
@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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
|
||||||
|
|
@ -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
|
||||||
|
|
@ -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
|
||||||
|
|
@ -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: "批量录入有待核查操作"
|
||||||
|
|
@ -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
|
||||||
|
|
@ -0,0 +1,5 @@
|
||||||
|
apiVersion: v1
|
||||||
|
kind: ServiceAccount
|
||||||
|
metadata:
|
||||||
|
name: atlas-alloy
|
||||||
|
namespace: item-atlas-observability
|
||||||
|
|
@ -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}
|
||||||
|
|
@ -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,也未接入两级缓存。
|
||||||
|
|
@ -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) 单独处理。
|
||||||
Loading…
Reference in New Issue