Реализовать наблюдаемость и доказательства уровня 4

This commit is contained in:
EgorAnti
2026-11-19 20:08:50 +03:00
parent 470d9d6f1e
commit 935de06050
195 changed files with 19333 additions and 53 deletions
@@ -0,0 +1,20 @@
package com.example.mtusi_messenger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
@SpringBootApplication
@EnableScheduling
public class MtusiMessengerApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(
MtusiMessengerApplication.class, args);
if (Boolean.parseBoolean(System.getenv("MIGRATE_ONLY"))) {
System.exit(SpringApplication.exit(context));
}
}
}
@@ -0,0 +1,83 @@
package com.example.mtusi_messenger.cache;
import com.example.mtusi_messenger.model.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.Optional;
import java.util.UUID;
@Component
public class UserCache {
private static final Logger log = LoggerFactory.getLogger(UserCache.class);
private static final String KEY_PREFIX = "messenger:user:";
private final StringRedisTemplate redis;
private final ObjectMapper mapper;
private final Duration ttl;
public UserCache(
StringRedisTemplate redis,
ObjectMapper mapper,
@Value("${messenger.cache.user-ttl-seconds:300}") long ttlSeconds
) {
if (ttlSeconds <= 0) {
throw new IllegalArgumentException("User cache TTL must be positive");
}
this.redis = redis;
this.mapper = mapper;
this.ttl = Duration.ofSeconds(ttlSeconds);
}
public Optional<User> find(UUID userId) {
try {
String value = redis.opsForValue().get(key(userId));
if (value == null) {
return Optional.empty();
}
User cachedUser = mapper.readValue(value, User.class);
if (cachedUser == null) {
log.warn("Ignoring null Redis user cache entry for {}", userId);
evict(userId);
return Optional.empty();
}
return Optional.of(cachedUser);
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; using PostgreSQL fallback");
return Optional.empty();
} catch (JsonProcessingException e) {
log.warn("Ignoring malformed Redis user cache entry for {}", userId);
evict(userId);
return Optional.empty();
}
}
public void put(User user) {
try {
redis.opsForValue().set(key(user.id()), mapper.writeValueAsString(user), ttl);
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; user was not cached");
} catch (JsonProcessingException e) {
throw new IllegalStateException("Cannot serialize user cache entry", e);
}
}
public void evict(UUID userId) {
try {
redis.delete(key(userId));
} catch (DataAccessException e) {
log.warn("Redis user cache is unavailable; cache eviction was skipped");
}
}
private String key(UUID userId) {
return KEY_PREFIX + userId;
}
}
@@ -0,0 +1,28 @@
package com.example.mtusi_messenger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer;
import tools.jackson.databind.cfg.CoercionAction;
import tools.jackson.databind.cfg.CoercionInputShape;
import tools.jackson.databind.type.LogicalType;
@Configuration
public class JacksonConfig {
@Bean
JsonMapperBuilderCustomizer strictStringTypes() {
return builder -> builder.withCoercionConfig(
LogicalType.Textual,
config -> {
config.setCoercion(
CoercionInputShape.Integer, CoercionAction.Fail);
config.setCoercion(
CoercionInputShape.Float, CoercionAction.Fail);
config.setCoercion(
CoercionInputShape.Boolean, CoercionAction.Fail);
}
);
}
}
@@ -0,0 +1,21 @@
package com.example.mtusi_messenger.config;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import org.springframework.context.annotation.Configuration;
@SecurityScheme(
name = "basicAuth",
type = SecuritySchemeType.HTTP,
scheme = "basic"
)
@SecurityScheme(
name = "bearerAuth",
type = SecuritySchemeType.HTTP,
scheme = "bearer",
bearerFormat = "opaque session token"
)
@Configuration
public class OpenApiConfig {
}
@@ -0,0 +1,14 @@
package com.example.mtusi_messenger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
public class PasswordConfig {
@Bean
PasswordEncoder passwordEncoder() {
return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8();
}
}
@@ -0,0 +1,57 @@
package com.example.mtusi_messenger.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitJobConfig {
@Bean
DirectExchange attachmentExchange(@Value("${messenger.jobs.exchange}") String name) {
return new DirectExchange(name, true, false);
}
@Bean
Queue attachmentQueue(
@Value("${messenger.jobs.queue}") String name,
@Value("${messenger.jobs.dead-letter-exchange}") String deadLetterExchange,
@Value("${messenger.jobs.dead-letter-routing-key}") String deadLetterRoutingKey) {
return QueueBuilder.durable(name)
.withArgument("x-dead-letter-exchange", deadLetterExchange)
.withArgument("x-dead-letter-routing-key", deadLetterRoutingKey)
.build();
}
@Bean
DirectExchange attachmentDeadLetterExchange(
@Value("${messenger.jobs.dead-letter-exchange}") String name) {
return new DirectExchange(name, true, false);
}
@Bean
Queue attachmentDeadLetterQueue(@Value("${messenger.jobs.dead-letter-queue}") String name) {
return QueueBuilder.durable(name).build();
}
@Bean
Binding attachmentBinding(
@Qualifier("attachmentQueue") Queue attachmentQueue,
@Qualifier("attachmentExchange") DirectExchange attachmentExchange,
@Value("${messenger.jobs.routing-key}") String routingKey) {
return BindingBuilder.bind(attachmentQueue).to(attachmentExchange).with(routingKey);
}
@Bean
Binding attachmentDeadLetterBinding(
@Qualifier("attachmentDeadLetterQueue") Queue queue,
@Qualifier("attachmentDeadLetterExchange") DirectExchange exchange,
@Value("${messenger.jobs.dead-letter-routing-key}") String routingKey) {
return BindingBuilder.bind(queue).to(exchange).with(routingKey);
}
}
@@ -0,0 +1,107 @@
package com.example.mtusi_messenger.config;
import com.example.mtusi_messenger.security.ApiAuthenticationFilter;
import com.example.mtusi_messenger.security.DatabaseAuthenticationProvider;
import com.example.mtusi_messenger.security.RestAuthenticationEntryPoint;
import com.example.mtusi_messenger.service.AuthenticationService;
import com.example.mtusi_messenger.web.ReadinessGuardFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
@Configuration
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class SecurityConfig {
@Bean
AuthenticationManager authenticationManager(DatabaseAuthenticationProvider provider) {
return new ProviderManager(provider);
}
@Bean
RestAuthenticationEntryPoint basicAuthenticationEntryPoint(ObjectMapper mapper) {
return new RestAuthenticationEntryPoint(
mapper,
"Basic realm=\"messenger\", charset=\"UTF-8\"");
}
@Bean
RestAuthenticationEntryPoint bearerAuthenticationEntryPoint(ObjectMapper mapper) {
return new RestAuthenticationEntryPoint(mapper, "Bearer realm=\"messenger\"");
}
@Bean
ApiAuthenticationFilter apiAuthenticationFilter(
AuthenticationManager authenticationManager,
AuthenticationService authenticationService,
@Qualifier("basicAuthenticationEntryPoint") RestAuthenticationEntryPoint basicAuthenticationEntryPoint,
@Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint
) {
return new ApiAuthenticationFilter(
authenticationManager,
authenticationService,
basicAuthenticationEntryPoint,
bearerAuthenticationEntryPoint);
}
@Bean
FilterRegistrationBean<ApiAuthenticationFilter> disableServletFilterRegistration(
ApiAuthenticationFilter filter
) {
var registration = new FilterRegistrationBean<>(filter);
registration.setEnabled(false);
return registration;
}
@Bean
FilterRegistrationBean<ReadinessGuardFilter> disableReadinessGuardServletRegistration(
ReadinessGuardFilter filter
) {
var registration = new FilterRegistrationBean<>(filter);
registration.setEnabled(false);
return registration;
}
@Bean
SecurityFilterChain securityFilterChain(
HttpSecurity http,
ApiAuthenticationFilter apiAuthenticationFilter,
ReadinessGuardFilter readinessGuardFilter,
@Qualifier("bearerAuthenticationEntryPoint") RestAuthenticationEntryPoint bearerAuthenticationEntryPoint
) throws Exception {
http
.csrf(csrf -> csrf.disable())
.formLogin(form -> form.disable())
.httpBasic(basic -> basic.disable())
.logout(logout -> logout.disable())
.requestCache(cache -> cache.disable())
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.exceptionHandling(errors -> errors
.authenticationEntryPoint(bearerAuthenticationEntryPoint))
.authorizeHttpRequests(authorize -> authorize
.requestMatchers(HttpMethod.GET, "/health/**").permitAll()
.requestMatchers(
"/swagger-ui.html",
"/swagger-ui/**",
"/v3/api-docs/**"
).permitAll()
.requestMatchers(HttpMethod.POST, "/api/v1/users").permitAll()
.anyRequest().authenticated())
// Refuse business traffic before authentication touches storage.
// Nginx retries this 503 on another peer and passively excludes
// the refusing replica according to max_fails/fail_timeout.
.addFilterBefore(readinessGuardFilter, AnonymousAuthenticationFilter.class)
.addFilterAfter(apiAuthenticationFilter, ReadinessGuardFilter.class);
return http.build();
}
}
@@ -0,0 +1,19 @@
package com.example.mtusi_messenger.config;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebConfig {
@Bean
ObjectMapper objectMapper() {
return JsonMapper.builder().findAndAddModules()
.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true)
.build();
}
}
@@ -0,0 +1,75 @@
package com.example.mtusi_messenger.controller;
import com.example.mtusi_messenger.dto.AttachmentResponse;
import com.example.mtusi_messenger.model.Attachment;
import com.example.mtusi_messenger.security.SessionPrincipal;
import com.example.mtusi_messenger.service.AttachmentService;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import static com.example.mtusi_messenger.service.UuidValidator.parse;
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1")
@SecurityRequirement(name = "bearerAuth")
public class AttachmentController {
private final AttachmentService attachments;
@PostMapping(value = "/chats/{chatId}/attachments",
consumes = {"image/png", "image/jpeg"},
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<AttachmentResponse> upload(
@AuthenticationPrincipal SessionPrincipal principal,
@PathVariable String chatId,
@RequestParam String filename,
@RequestHeader(HttpHeaders.CONTENT_TYPE) String contentType,
HttpServletRequest request
) throws IOException {
Attachment attachment = attachments.upload(parse(chatId), principal.user().id(), filename,
contentType, request.getContentLengthLong(), request.getInputStream());
return ResponseEntity.status(HttpStatus.ACCEPTED).body(AttachmentResponse.from(attachment));
}
@GetMapping("/attachments/{attachmentId}")
public AttachmentResponse metadata(
@AuthenticationPrincipal SessionPrincipal principal,
@PathVariable String attachmentId
) {
return AttachmentResponse.from(attachments.getAccessible(parse(attachmentId), principal.user().id()));
}
@GetMapping("/attachments/{attachmentId}/content")
public ResponseEntity<byte[]> download(
@AuthenticationPrincipal SessionPrincipal principal,
@PathVariable String attachmentId,
@RequestParam(defaultValue = "original") String variant
) {
AttachmentService.Download download = attachments.download(
parse(attachmentId), principal.user().id(), variant);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(download.contentType()))
.contentLength(download.bytes().length)
.header(HttpHeaders.CONTENT_DISPOSITION, ContentDisposition.inline()
.filename(download.filename(), StandardCharsets.UTF_8).build().toString())
.body(download.bytes());
}
}
@@ -0,0 +1,83 @@
package com.example.mtusi_messenger.controller;
import com.example.mtusi_messenger.exception.ApiExceptions;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import com.example.mtusi_messenger.dto.*;
import com.example.mtusi_messenger.model.Chat;
import com.example.mtusi_messenger.service.ChatService;
import com.example.mtusi_messenger.security.SessionPrincipal;
import java.util.List;
import java.util.UUID;
import static com.example.mtusi_messenger.service.UuidValidator.parse;
@RestController
@RequestMapping("/api/v1/chats")
@SecurityRequirement(name = "bearerAuth")
@RequiredArgsConstructor
public class ChatController {
private final ChatService chats;
@PostMapping
public ResponseEntity<ChatResponse> create(@AuthenticationPrincipal SessionPrincipal principal,
@Valid @RequestBody CreateChatRequest body
) {
UUID userId = principal.user().id();
Chat c = chats.create(body, userId);
return ResponseEntity.status(HttpStatus.CREATED).body(ChatResponse.from(c));
}
@GetMapping
public ChatPageResponse list(@AuthenticationPrincipal SessionPrincipal principal,
@RequestParam(required = false) String limit,
@RequestParam(required = false) String cursor
) {
UUID userId = principal.user().id();
int parsedLimit = validateLimit(limit);
validateCursorPresence(cursor);
List<Chat> page = chats.page(userId, parsedLimit, cursor);
boolean hasNext = page.size() > parsedLimit;
if (hasNext) page = page.subList(0, parsedLimit);
return new ChatPageResponse(page.stream().map(ChatResponse::from).toList(), page.isEmpty() ? null :
chats.nextCursor(userId, page.get(page.size() - 1), hasNext));
}
@GetMapping("/{chatId}")
public ChatResponse get(@AuthenticationPrincipal SessionPrincipal principal,
@PathVariable String chatId
) {
UUID userId = principal.user().id();
return ChatResponse.from(chats.getAccessible(parse(chatId), userId));
}
private static int validateLimit(String limit) {
if (limit == null) {
return 50;
}
if (!limit.matches("[0-9]+")) {
throw ApiExceptions.invalid("Invalid limit");
}
try {
int value = Integer.parseInt(limit);
if (value < 1 || value > 100) {
throw ApiExceptions.invalid("Invalid limit");
}
return value;
} catch (NumberFormatException ex) {
throw ApiExceptions.invalid("Invalid limit");
}
}
private static void validateCursorPresence(String c) {
if (c != null && c.isBlank()) throw ApiExceptions.invalid("Invalid cursor");
}
}
@@ -0,0 +1,32 @@
package com.example.mtusi_messenger.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.mtusi_messenger.dto.HealthResponse;
import com.example.mtusi_messenger.exception.ApiExceptions;
import com.example.mtusi_messenger.service.ReadinessService;
@RestController
public class HealthController {
private final ReadinessService readiness;
public HealthController(ReadinessService readiness) {
this.readiness = readiness;
}
@GetMapping("/health/live")
public ResponseEntity<HealthResponse> live() {
return ResponseEntity.ok(new HealthResponse("ok"));
}
@GetMapping("/health/ready")
public ResponseEntity<HealthResponse> ready() {
// Always probe dependencies, even after a failure, so a restored schema
// can move this process back to ACCEPTING_TRAFFIC without a restart.
if (!readiness.probeDependencies() || !readiness.acceptsBusinessTraffic()) {
throw ApiExceptions.unavailable("Application is not accepting traffic");
}
return ResponseEntity.ok(new HealthResponse("ok"));
}
}
@@ -0,0 +1,79 @@
package com.example.mtusi_messenger.controller;
import com.example.mtusi_messenger.exception.ApiExceptions;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import com.example.mtusi_messenger.dto.*;
import com.example.mtusi_messenger.model.Message;
import com.example.mtusi_messenger.service.MessageService;
import com.example.mtusi_messenger.security.SessionPrincipal;
import java.util.List;
import java.util.UUID;
import static com.example.mtusi_messenger.service.UuidValidator.parse;
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/v1/chats/{chatId}/messages")
@SecurityRequirement(name = "bearerAuth")
public class MessageController {
private static final String IDEMPOTENCY_KEY_PATTERN = "[A-Za-z0-9._:-]{1,128}";
private final MessageService messages;
@PostMapping
public ResponseEntity<MessageResponse> create(@AuthenticationPrincipal SessionPrincipal principal,
@PathVariable String chatId,
@RequestHeader(name = "Idempotency-Key", required = false) String idempotencyKey,
@Valid @RequestBody CreateMessageRequest body
) {
if (idempotencyKey == null || !idempotencyKey.matches(IDEMPOTENCY_KEY_PATTERN)) {
throw ApiExceptions.invalid("Invalid or missing Idempotency-Key");
}
UUID userId = principal.user().id();
UUID parsedChatId = parse(chatId);
Message m = messages.create(parsedChatId, userId, body, idempotencyKey);
return ResponseEntity.status(HttpStatus.CREATED).body(MessageResponse.from(m));
}
@GetMapping
public MessagePageResponse list(@AuthenticationPrincipal SessionPrincipal principal,
@PathVariable String chatId,
@RequestParam(required = false) String limit,
@RequestParam(required=false) String cursor
) {
UUID userId = principal.user().id();
UUID parsedChatId = parse(chatId);
int parsedLimit = validateLimit(limit);
if (cursor != null && cursor.isBlank()) throw ApiExceptions.invalid("Invalid cursor");
List<Message> page = messages.page(parsedChatId, userId, parsedLimit, cursor);
boolean hasNext = page.size() > parsedLimit; if (hasNext) page = page.subList(0, parsedLimit);
return new MessagePageResponse(page.stream().map(MessageResponse::from).toList(),
page.isEmpty() ? null : messages.nextCursor(parsedChatId, page.get(page.size()-1), hasNext));
}
private static int validateLimit(String limit) {
if (limit == null) {
return 50;
}
if (!limit.matches("[0-9]+")) {
throw ApiExceptions.invalid("Invalid limit");
}
try {
int value = Integer.parseInt(limit);
if (value < 1 || value > 100) {
throw ApiExceptions.invalid("Invalid limit");
}
return value;
} catch (NumberFormatException ex) {
throw ApiExceptions.invalid("Invalid limit");
}
}
}
@@ -0,0 +1,41 @@
package com.example.mtusi_messenger.controller;
import com.example.mtusi_messenger.dto.SessionResponse;
import com.example.mtusi_messenger.dto.UserResponse;
import com.example.mtusi_messenger.service.AuthenticationService;
import com.example.mtusi_messenger.model.User;
import com.example.mtusi_messenger.security.SessionPrincipal;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api/v1/auth/sessions")
@RequiredArgsConstructor
public class SessionController {
private final AuthenticationService authentication;
@PostMapping
@SecurityRequirement(name = "basicAuth")
public ResponseEntity<SessionResponse> create(@AuthenticationPrincipal User user) {
var issued = authentication.issueSession(user);
return ResponseEntity.status(HttpStatus.CREATED).body(new SessionResponse(
issued.token(),
"Bearer",
issued.expiresAt(),
UserResponse.from(issued.user())));
}
@DeleteMapping("/current")
@SecurityRequirement(name = "bearerAuth")
public ResponseEntity<Void> revoke(@AuthenticationPrincipal SessionPrincipal principal) {
authentication.revoke(principal);
return ResponseEntity.noContent().build();
}
}
@@ -0,0 +1,32 @@
package com.example.mtusi_messenger.controller;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import com.example.mtusi_messenger.dto.*;
import com.example.mtusi_messenger.service.UserService;
import com.example.mtusi_messenger.security.SessionPrincipal;
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class UserController {
private final UserService users;
@PostMapping
public ResponseEntity<UserResponse> create(@Valid @RequestBody CreateUserRequest request) {
var user = users.create(request);
return ResponseEntity.status(HttpStatus.CREATED).body(UserResponse.from(user));
}
@GetMapping("/me")
@SecurityRequirement(name = "bearerAuth")
public UserResponse me(@AuthenticationPrincipal SessionPrincipal principal) {
return UserResponse.from(principal.user());
}
}
@@ -0,0 +1,36 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.model.Attachment;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public record AttachmentResponse(UUID id,
UUID chat_id,
UUID owner_id,
String filename,
String content_type,
long size_bytes,
String sha256,
String status,
List<AttachmentVariantResponse> variants,
String error_code,
Instant created_at,
Instant updated_at) {
public static AttachmentResponse from(Attachment attachment) {
return new AttachmentResponse(
attachment.id(),
attachment.chatId(),
attachment.ownerId(),
attachment.filename(),
attachment.contentType(),
attachment.sizeBytes(),
attachment.sha256(),
attachment.status(),
attachment.variants().stream().map(AttachmentVariantResponse::from).toList(),
attachment.errorCode(),
attachment.createdAt(),
attachment.updatedAt());
}
}
@@ -0,0 +1,16 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.model.AttachmentVariant;
public record AttachmentVariantResponse(String name,
String content_type,
long size_bytes,
int width,
int height,
String sha256) {
public static AttachmentVariantResponse from(AttachmentVariant variant) {
return new AttachmentVariantResponse(
variant.name(), variant.contentType(), variant.sizeBytes(),
variant.width(), variant.height(), variant.sha256());
}
}
@@ -0,0 +1,8 @@
package com.example.mtusi_messenger.dto;
import java.util.List;
public record ChatPageResponse(
List<ChatResponse> items,
String next_cursor
) {}
@@ -0,0 +1,18 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.model.Chat;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public record ChatResponse(UUID id,
String title,
List<UUID> member_ids,
Instant created_at) {
public static ChatResponse from(Chat c) {
return new ChatResponse(
c.id(),
c.title(),
c.memberIds(),
c.createdAt()); }
}
@@ -0,0 +1,19 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.web.NotUnicodeBlank;
import com.example.mtusi_messenger.web.UnicodeSize;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Size;
import java.util.List;
import java.util.UUID;
public record CreateChatRequest(
@NotUnicodeBlank
@UnicodeSize(min = 1, max = 100)
String title,
@NotEmpty
@Size(min = 1, max = 100)
List<UUID> member_ids
) {}
@@ -0,0 +1,31 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.web.UnicodeSize;
import jakarta.validation.constraints.AssertTrue;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import java.util.HashSet;
import java.util.List;
import java.util.UUID;
public record CreateMessageRequest(
@NotNull @UnicodeSize(max = 4000) String text,
@Size(max = 10) List<UUID> attachment_ids
) {
public CreateMessageRequest {
attachment_ids = attachment_ids == null ? List.of() : List.copyOf(attachment_ids);
}
@AssertTrue(message = "text or attachment_ids must be present")
public boolean isContentPresent() {
return text != null && (!text.isBlank() || !attachment_ids.isEmpty());
}
@AssertTrue(message = "attachment_ids must be unique and non-null")
public boolean isAttachmentIdsValid() {
return attachment_ids != null
&& attachment_ids.stream().noneMatch(java.util.Objects::isNull)
&& new HashSet<>(attachment_ids).size() == attachment_ids.size();
}
}
@@ -0,0 +1,20 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.web.NotUnicodeBlank;
import com.example.mtusi_messenger.web.UnicodeSize;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.Pattern;
public record CreateUserRequest(
@NotBlank
@Pattern(regexp = "[a-z0-9_]{3,32}")
String username,
@NotUnicodeBlank
@UnicodeSize(min = 1, max = 100)
String display_name,
@NotUnicodeBlank
@UnicodeSize(min = 12, max = 128)
String password
) {}
@@ -0,0 +1,8 @@
package com.example.mtusi_messenger.dto;
public record ErrorResponse(ErrorBody error) {
public record ErrorBody(String code,
String message,
String request_id)
{}
}
@@ -0,0 +1,3 @@
package com.example.mtusi_messenger.dto;
public record HealthResponse(String status) {}
@@ -0,0 +1,8 @@
package com.example.mtusi_messenger.dto;
import java.util.List;
public record MessagePageResponse(
List<MessageResponse> items,
String next_cursor
) {}
@@ -0,0 +1,22 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.model.Message;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public record MessageResponse(UUID id,
UUID chat_id,
UUID sender_id,
String text,
Instant created_at,
List<UUID> attachment_ids) {
public static MessageResponse from(Message m) {
return new MessageResponse(m.id(),
m.chatId(),
m.senderId(),
m.text(),
m.createdAt(),
m.attachmentIds());
}
}
@@ -0,0 +1,10 @@
package com.example.mtusi_messenger.dto;
import java.time.Instant;
public record SessionResponse(
String token,
String token_type,
Instant expires_at,
UserResponse user
) {}
@@ -0,0 +1,18 @@
package com.example.mtusi_messenger.dto;
import com.example.mtusi_messenger.model.User;
import java.time.Instant;
import java.util.UUID;
public record UserResponse(UUID id,
String username,
String display_name,
Instant created_at) {
public static UserResponse from(User u) {
return new UserResponse(
u.id(),
u.username(),
u.displayName(),
u.createdAt());
}
}
@@ -0,0 +1,14 @@
package com.example.mtusi_messenger.exception;
import org.springframework.http.HttpStatus;
public class ApiException extends RuntimeException {
private final String code; private final HttpStatus status; private final String authenticate;
public ApiException(String code, HttpStatus status, String message) { this(code, status, message, null); }
public ApiException(String code, HttpStatus status, String message, String authenticate) {
super(message); this.code = code; this.status = status; this.authenticate = authenticate;
}
public String code() { return code; }
public HttpStatus status() { return status; }
public String authenticate() { return authenticate; }
}
@@ -0,0 +1,17 @@
package com.example.mtusi_messenger.exception;
import org.springframework.http.HttpStatus;
public final class ApiExceptions {
private ApiExceptions() {}
public static ApiException invalid(String m) { return new ApiException("invalid_request", HttpStatus.BAD_REQUEST, m); }
public static ApiException unauthorized(String m) { return unauthorizedBearer(m); }
public static ApiException unauthorizedBasic(String m) { return new ApiException("unauthorized", HttpStatus.UNAUTHORIZED, m, "Basic realm=\"messenger\", charset=\"UTF-8\""); }
public static ApiException unauthorizedBearer(String m) { return new ApiException("unauthorized", HttpStatus.UNAUTHORIZED, m, "Bearer realm=\"messenger\""); }
public static ApiException notFound(String m) { return new ApiException("not_found", HttpStatus.NOT_FOUND, m); }
public static ApiException conflict(String m) { return new ApiException("conflict", HttpStatus.CONFLICT, m); }
public static ApiException payloadTooLarge(String m) { return new ApiException("payload_too_large", HttpStatus.PAYLOAD_TOO_LARGE, m); }
public static ApiException unsupportedMediaType(String m) { return new ApiException("unsupported_media_type", HttpStatus.UNSUPPORTED_MEDIA_TYPE, m); }
public static ApiException tooManyRequests(String m) { return new ApiException("too_many_requests", HttpStatus.TOO_MANY_REQUESTS, m); }
public static ApiException unavailable(String m) { return new ApiException("unavailable", HttpStatus.SERVICE_UNAVAILABLE, m); }
}
@@ -0,0 +1,38 @@
package com.example.mtusi_messenger.model;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public record Attachment(UUID id,
UUID chatId,
UUID ownerId,
String filename,
String contentType,
long sizeBytes,
String sha256,
String objectKey,
String stagingKey,
String status,
List<AttachmentVariant> variants,
String errorCode,
Instant createdAt,
Instant updatedAt) {
public Attachment {
variants = variants == null ? List.of() : List.copyOf(variants);
}
public Attachment(UUID id,
UUID chatId,
UUID ownerId,
String filename,
String contentType,
long sizeBytes,
String sha256,
String objectKey,
Instant createdAt,
Instant updatedAt) {
this(id, chatId, ownerId, filename, contentType, sizeBytes, sha256, objectKey,
null, "ready", List.of(), null, createdAt, updatedAt);
}
}
@@ -0,0 +1,40 @@
package com.example.mtusi_messenger.model;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.time.Instant;
import java.util.UUID;
public record AttachmentJob(
@JsonProperty("schema_version") int schemaVersion,
@JsonProperty("job_id") UUID jobId,
String type,
@JsonProperty("attachment_id") UUID attachmentId,
@JsonProperty("pipeline_version") int pipelineVersion,
int attempt,
@JsonProperty("created_at") Instant createdAt) {
public static final int SCHEMA_VERSION = 1;
public static final int MIN_PIPELINE_VERSION = 1;
public static final int CURRENT_PIPELINE_VERSION = 2;
public static final String TYPE = "attachment.process.v1";
public AttachmentJob {
if (schemaVersion != SCHEMA_VERSION || !TYPE.equals(type)
|| pipelineVersion < MIN_PIPELINE_VERSION
|| pipelineVersion > CURRENT_PIPELINE_VERSION || attempt < 1) {
throw new IllegalArgumentException("Unsupported attachment job message");
}
}
public static AttachmentJob first(
UUID jobId, UUID attachmentId, int pipelineVersion, Instant createdAt) {
return new AttachmentJob(SCHEMA_VERSION, jobId, TYPE, attachmentId,
pipelineVersion, 1, createdAt);
}
public AttachmentJob nextAttempt(int nextAttempt) {
return new AttachmentJob(schemaVersion, jobId, type, attachmentId,
pipelineVersion, nextAttempt, createdAt);
}
}
@@ -0,0 +1,10 @@
package com.example.mtusi_messenger.model;
public record AttachmentVariant(String name,
String contentType,
long sizeBytes,
int width,
int height,
String sha256,
String objectKey) {
}
@@ -0,0 +1,11 @@
package com.example.mtusi_messenger.model;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public record Chat(UUID id, String title, List<UUID> memberIds, Instant createdAt) {
public Chat {
memberIds = List.copyOf(memberIds);
}
}
@@ -0,0 +1,3 @@
package com.example.mtusi_messenger.model;
public record IdempotentMessage(byte[] requestHash, Message message) {}
@@ -0,0 +1,16 @@
package com.example.mtusi_messenger.model;
import java.time.Instant;
import java.util.List;
import java.util.UUID;
public record Message(UUID id,
UUID chatId,
UUID senderId,
String text,
Instant createdAt,
List<UUID> attachmentIds) {
public Message {
attachmentIds = attachmentIds == null ? List.of() : List.copyOf(attachmentIds);
}
}
@@ -0,0 +1,35 @@
package com.example.mtusi_messenger.model;
import java.time.Instant;
import java.util.UUID;
public record MessageKey(Instant createdAt, UUID id)
implements Comparable<MessageKey> {
private static int compareUuidV7(UUID a, UUID b) {
int result = Long.compareUnsigned(
a.getMostSignificantBits(),
b.getMostSignificantBits()
);
if (result != 0) {
return result;
}
return Long.compareUnsigned(
a.getLeastSignificantBits(),
b.getLeastSignificantBits()
);
}
@Override
public int compareTo(MessageKey other) {
int result = createdAt.compareTo(other.createdAt);
if (result != 0) {
return result;
}
return compareUuidV7(id, other.id);
}
}
@@ -0,0 +1,15 @@
package com.example.mtusi_messenger.model;
import java.time.Instant;
import java.util.UUID;
public record Session(UUID id, UUID userId, byte[] tokenHash, Instant createdAt, Instant expiresAt) {
public Session {
tokenHash = tokenHash.clone();
}
@Override
public byte[] tokenHash() {
return tokenHash.clone();
}
}
@@ -0,0 +1,6 @@
package com.example.mtusi_messenger.model;
import java.time.Instant;
import java.util.UUID;
public record User(UUID id, String username, String displayName, Instant createdAt) {}
@@ -0,0 +1,45 @@
package com.example.mtusi_messenger.observability;
import com.example.mtusi_messenger.repository.AttachmentRepository.TraceContext;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import io.opentelemetry.context.propagation.TextMapGetter;
import io.opentelemetry.context.propagation.TextMapPropagator;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class DurableTraceContext {
private static final TextMapGetter<Map<String, String>> GETTER = new TextMapGetter<>() {
@Override
public Iterable<String> keys(Map<String, String> carrier) {
return carrier.keySet();
}
@Override
public String get(Map<String, String> carrier, String key) {
return carrier.get(key);
}
};
private final TextMapPropagator propagator = GlobalOpenTelemetry.getPropagators()
.getTextMapPropagator();
public TraceContext capture() {
Map<String, String> carrier = new HashMap<>();
propagator.inject(Context.current(), carrier, Map::put);
return new TraceContext(carrier.get("traceparent"), carrier.get("tracestate"));
}
public Scope restore(TraceContext traceContext) {
Map<String, String> carrier = new HashMap<>();
carrier.put("traceparent", traceContext.traceparent());
if (traceContext.tracestate() != null && !traceContext.tracestate().isBlank()) {
carrier.put("tracestate", traceContext.tracestate());
}
return propagator.extract(Context.root(), carrier, GETTER).makeCurrent();
}
}
@@ -0,0 +1,77 @@
package com.example.mtusi_messenger.observability;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.DoubleHistogram;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.atomic.AtomicLong;
/** Low-cardinality business metrics required by contracts/observability.md. */
@Component
@ConditionalOnProperty(name = "messenger.role", havingValue = "worker")
public class JobTelemetry {
private static final AttributeKey<String> JOB_TYPE = AttributeKey.stringKey("job.type");
private static final AttributeKey<String> OUTCOME = AttributeKey.stringKey("outcome");
private static final String ATTACHMENT_JOB = "attachment_variant";
private final LongCounter processed;
private final DoubleHistogram processingDuration;
private final DoubleHistogram timeToReady;
private final AtomicLong busy = new AtomicLong();
public JobTelemetry(@Value("${spring.rabbitmq.listener.simple.concurrency:2}") long capacity) {
Meter meter = GlobalOpenTelemetry.get().meterBuilder("messenger-jobs")
.setInstrumentationVersion("1.0.0")
.build();
processed = meter.counterBuilder("messenger.jobs.processed")
.setDescription("Completed attachment job attempts")
.build();
processingDuration = meter.histogramBuilder("messenger.job.processing.duration")
.setDescription("Attachment job attempt duration")
.setUnit("s")
.build();
timeToReady = meter.histogramBuilder("messenger.attachment.time_to_ready")
.setDescription("Time from durable acceptance to ready state")
.setUnit("s")
.build();
meter.gaugeBuilder("messenger.worker.busy")
.ofLongs()
.setDescription("Workers currently processing an attachment job")
.buildWithCallback(measurement -> measurement.record(busy.get()));
meter.gaugeBuilder("messenger.worker.capacity")
.ofLongs()
.setDescription("Configured attachment worker capacity")
.buildWithCallback(measurement -> measurement.record(capacity));
}
public long started() {
busy.incrementAndGet();
return System.nanoTime();
}
public void finished(long startedNanos, Instant acceptedAt, String outcome) {
busy.updateAndGet(current -> Math.max(0, current - 1));
Attributes attributes = Attributes.of(JOB_TYPE, ATTACHMENT_JOB, OUTCOME, outcome);
processed.add(1, attributes);
processingDuration.record(
Math.max(0, System.nanoTime() - startedNanos) / 1_000_000_000.0,
attributes);
if ("success".equals(outcome)) {
timeToReady.record(
Math.max(0, Duration.between(acceptedAt, Instant.now()).toMillis()) / 1000.0,
Attributes.of(JOB_TYPE, ATTACHMENT_JOB, OUTCOME, outcome));
}
}
public void malformedMessage() {
processed.add(1, Attributes.of(JOB_TYPE, ATTACHMENT_JOB, OUTCOME, "invalid_message"));
}
}
@@ -0,0 +1,71 @@
package com.example.mtusi_messenger.observability;
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.metrics.Meter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.concurrent.atomic.AtomicLong;
/** Samples the durable job queue without placing job or user identifiers in labels. */
@Component
@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true)
public class QueueTelemetry {
private static final Logger log = LoggerFactory.getLogger(QueueTelemetry.class);
private static final AttributeKey<String> QUEUE_NAME = AttributeKey.stringKey("messaging.destination.name");
private final JdbcTemplate jdbc;
private final AtomicLong depth = new AtomicLong();
private final AtomicLong oldestAgeSeconds = new AtomicLong();
private final Attributes queueAttributes;
public QueueTelemetry(
JdbcTemplate jdbc,
@Value("${messenger.jobs.queue}") String queueName) {
this.jdbc = jdbc;
this.queueAttributes = Attributes.of(QUEUE_NAME, queueName);
Meter meter = GlobalOpenTelemetry.get().meterBuilder("messenger-queue")
.setInstrumentationVersion("1.0.0")
.build();
meter.gaugeBuilder("messenger.queue.depth")
.ofLongs()
.setDescription("Durable queued or processing attachment jobs")
.buildWithCallback(measurement -> measurement.record(depth.get(), queueAttributes));
meter.gaugeBuilder("messenger.queue.oldest_job.age")
.ofLongs()
.setDescription("Age of the oldest non-terminal attachment job")
.setUnit("s")
.buildWithCallback(measurement -> measurement.record(oldestAgeSeconds.get(), queueAttributes));
}
@Scheduled(fixedDelayString = "${messenger.observability.queue-poll-interval:5s}")
public void sample() {
try {
QueueSnapshot snapshot = jdbc.queryForObject("""
SELECT count(*) AS depth,
COALESCE(EXTRACT(EPOCH FROM
(clock_timestamp() - min(created_at))), 0)::bigint AS oldest_age
FROM attachment_jobs
WHERE status IN ('queued', 'processing')
""", (rs, row) -> new QueueSnapshot(rs.getLong("depth"), rs.getLong("oldest_age")));
if (snapshot != null) {
depth.set(snapshot.depth());
oldestAgeSeconds.set(Math.max(0, snapshot.oldestAgeSeconds()));
}
} catch (RuntimeException error) {
log.atWarn()
.addKeyValue("event", "queue_metrics_sample_failed")
.log("Queue telemetry sample failed: {}", error.getClass().getSimpleName());
}
}
private record QueueSnapshot(long depth, long oldestAgeSeconds) {
}
}
@@ -0,0 +1,65 @@
package com.example.mtusi_messenger.queue;
import com.example.mtusi_messenger.model.AttachmentJob;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.Duration;
@Component
public class AttachmentJobPublisher {
private final RabbitTemplate rabbit;
private final ObjectMapper mapper;
private final String exchange;
private final String routingKey;
private final long confirmTimeoutMillis;
public AttachmentJobPublisher(
RabbitTemplate rabbit,
ObjectMapper mapper,
@Value("${messenger.jobs.exchange}") String exchange,
@Value("${messenger.jobs.routing-key}") String routingKey,
@Value("${messenger.jobs.publish-confirm-timeout:5s}") Duration confirmTimeout) {
this.rabbit = rabbit;
this.mapper = mapper;
this.exchange = exchange;
this.routingKey = routingKey;
this.confirmTimeoutMillis = confirmTimeout.toMillis();
this.rabbit.setMandatory(true);
}
public void publish(AttachmentJob job) {
try {
byte[] body = mapper.writeValueAsBytes(job);
MessageProperties properties = new MessageProperties();
properties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
properties.setContentEncoding("UTF-8");
properties.setDeliveryMode(MessageDeliveryMode.PERSISTENT);
properties.setMessageId(job.jobId().toString());
properties.setHeader("schema_version", job.schemaVersion());
Message message = new Message(body, properties);
rabbit.invoke(operations -> {
operations.send(exchange, routingKey, message);
operations.waitForConfirmsOrDie(confirmTimeoutMillis);
return null;
});
} catch (JsonProcessingException error) {
throw new JobPublishException("Cannot encode attachment job", error);
} catch (RuntimeException error) {
throw new JobPublishException("RabbitMQ did not confirm attachment job", error);
}
}
public static final class JobPublishException extends RuntimeException {
public JobPublishException(String message, Throwable cause) {
super(message, cause);
}
}
}
@@ -0,0 +1,57 @@
package com.example.mtusi_messenger.queue;
import com.example.mtusi_messenger.repository.AttachmentRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;
import java.time.Clock;
@Component
@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true)
public class ExpiredLeaseReaper {
private static final Logger log = LoggerFactory.getLogger(ExpiredLeaseReaper.class);
private final AttachmentRepository attachments;
private final RetryPolicy retryPolicy;
private final TransactionTemplate transaction;
private final int maxAttempts;
private final Clock clock = Clock.systemUTC();
public ExpiredLeaseReaper(
AttachmentRepository attachments,
RetryPolicy retryPolicy,
TransactionTemplate transaction,
@Value("${messenger.jobs.max-attempts:5}") int maxAttempts) {
this.attachments = attachments;
this.retryPolicy = retryPolicy;
this.transaction = transaction;
this.maxAttempts = maxAttempts;
}
@Scheduled(fixedDelayString = "${messenger.jobs.lease-reaper-interval:5s}")
public void recoverExpired() {
for (var job : attachments.findExpiredJobs(50)) {
try {
transaction.executeWithoutResult(status -> {
if (job.attempt() >= maxAttempts) {
attachments.failExpired(job.jobId(), job.attachmentId(),
job.pipelineVersion(), "retry_exhausted");
} else {
int nextAttempt = job.attempt() + 1;
attachments.requeueExpired(
job.jobId(), job.attachmentId(), job.pipelineVersion(),
nextAttempt, "processing_timeout",
clock.instant().plus(retryPolicy.delayForAttempt(nextAttempt)));
}
});
} catch (RuntimeException error) {
log.warn("Expired attachment lease recovery postponed for job {}", job.jobId());
return;
}
}
}
}
@@ -0,0 +1,39 @@
package com.example.mtusi_messenger.queue;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.concurrent.ThreadLocalRandom;
@Component
public class RetryPolicy {
private final long baseDelayMillis;
private final long maxDelayMillis;
public RetryPolicy(
@Value("${messenger.jobs.retry-base-delay:1s}") Duration baseDelay,
@Value("${messenger.jobs.retry-max-delay:30s}") Duration maxDelay) {
if (baseDelay.isNegative() || baseDelay.isZero() || maxDelay.compareTo(baseDelay) < 0) {
throw new IllegalArgumentException("Invalid retry delay configuration");
}
this.baseDelayMillis = baseDelay.toMillis();
this.maxDelayMillis = maxDelay.toMillis();
}
public Duration delayForAttempt(int nextAttempt) {
int exponent = Math.max(0, Math.min(30, nextAttempt - 2));
long exponential;
try {
exponential = Math.multiplyExact(baseDelayMillis, 1L << exponent);
} catch (ArithmeticException overflow) {
exponential = maxDelayMillis;
}
long ceiling = Math.min(maxDelayMillis, exponential);
long floor = Math.max(1, ceiling / 2);
long jittered = floor == ceiling
? ceiling
: ThreadLocalRandom.current().nextLong(floor, ceiling + 1);
return Duration.ofMillis(jittered);
}
}
@@ -0,0 +1,47 @@
package com.example.mtusi_messenger.queue;
import com.example.mtusi_messenger.repository.AttachmentRepository;
import com.example.mtusi_messenger.observability.DurableTraceContext;
import io.opentelemetry.context.Scope;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true)
public class UnpublishedJobRepublisher {
private static final Logger log = LoggerFactory.getLogger(UnpublishedJobRepublisher.class);
private final AttachmentRepository attachments;
private final AttachmentJobPublisher publisher;
private final DurableTraceContext tracing;
public UnpublishedJobRepublisher(AttachmentRepository attachments,
AttachmentJobPublisher publisher,
DurableTraceContext tracing) {
this.attachments = attachments;
this.publisher = publisher;
this.tracing = tracing;
}
@Scheduled(fixedDelayString = "${messenger.jobs.republish-interval:5s}")
public void publishPending() {
for (var job : attachments.findUnpublishedJobs(50)) {
try {
var traceContext = attachments.findTraceContext(job.jobId());
if (traceContext.isPresent()) {
try (Scope ignored = tracing.restore(traceContext.get())) {
publisher.publish(job);
}
} else {
publisher.publish(job);
}
attachments.markPublished(job.jobId());
} catch (RuntimeException error) {
log.warn("Attachment job publication postponed for job {}", job.jobId());
return;
}
}
}
}
@@ -0,0 +1,45 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Attachment;
import com.example.mtusi_messenger.model.AttachmentJob;
import com.example.mtusi_messenger.model.AttachmentVariant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.Set;
import java.time.Duration;
import java.time.Instant;
public interface AttachmentRepository {
Attachment saveQueued(Attachment attachment, AttachmentJob job);
Optional<Attachment> findById(UUID id);
List<Attachment> findAllByIdsInChat(UUID chatId, List<UUID> ids);
Set<String> findAllObjectKeys();
Set<String> findActiveStagingKeys();
void markPublished(UUID jobId);
boolean markPublishFaultInjected(UUID jobId);
List<AttachmentJob> findUnpublishedJobs(int limit);
Optional<TraceContext> findTraceContext(UUID jobId);
int currentAttempt(UUID jobId);
boolean claim(UUID jobId, UUID attachmentId, int pipelineVersion,
int attempt, UUID leaseToken, Duration leaseDuration);
boolean markBeforeEffectFaultInjected(UUID jobId, UUID leaseToken);
boolean markAfterEffectFaultInjected(UUID jobId, UUID leaseToken);
boolean markQueuedForRetry(UUID jobId, UUID attachmentId, int pipelineVersion, UUID leaseToken,
int nextAttempt, String errorCode, Instant nextAttemptAt);
CompletionResult markReady(UUID jobId, UUID attachmentId, UUID leaseToken, int pipelineVersion,
List<AttachmentVariant> variants, boolean injectCrashAfterCommit);
boolean markFailed(UUID jobId, UUID attachmentId, int pipelineVersion,
UUID leaseToken, String errorCode);
List<AttachmentJob> findExpiredJobs(int limit);
boolean requeueExpired(UUID jobId, UUID attachmentId, int pipelineVersion, int nextAttempt,
String errorCode, Instant nextAttemptAt);
boolean failExpired(UUID jobId, UUID attachmentId, int pipelineVersion, String errorCode);
record CompletionResult(boolean completed, boolean crashAfterCommit) {
}
record TraceContext(String traceparent, String tracestate) {
}
}
@@ -0,0 +1,14 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Chat;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public interface ChatRepository {
Chat save(Chat chat);
Optional<Chat> findById(UUID id);
boolean isMember(UUID chatId, UUID userId);
List<Chat> findAllForUser(UUID userId);
List<Chat> findPageForUser(UUID userId, UUID afterId, java.time.Instant afterCreatedAt, int limitPlusOne);
}
@@ -0,0 +1,18 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Message;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
public interface MessageRepository {
Message save(Message message);
void lockIdempotencyScope(UUID userId, String method, String path, String key);
void deleteExpiredIdempotency(UUID userId, String method, String path, String key, Instant expiresBefore);
Optional<com.example.mtusi_messenger.model.IdempotentMessage> findIdempotent(
UUID userId, String method, String path, String key);
void saveIdempotency(UUID userId, String method, String path, String key,
byte[] requestHash, UUID messageId, Instant createdAt);
List<Message> findPage(UUID chatId, Instant afterCreatedAt, UUID afterId, int limitPlusOne);
}
@@ -0,0 +1,402 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Attachment;
import com.example.mtusi_messenger.model.AttachmentJob;
import com.example.mtusi_messenger.model.AttachmentVariant;
import com.example.mtusi_messenger.observability.DurableTraceContext;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
@Repository
public class PostgresAttachmentRepository implements AttachmentRepository {
private static final String COLUMNS = """
id, chat_id, owner_id, filename, content_type, size_bytes,
sha256, object_key, staging_key, status, error_code, created_at, updated_at
""";
private final JdbcTemplate jdbc;
private final DurableTraceContext tracing;
public PostgresAttachmentRepository(JdbcTemplate jdbc, DurableTraceContext tracing) {
this.jdbc = jdbc;
this.tracing = tracing;
}
@Override
public Attachment saveQueued(Attachment attachment, AttachmentJob job) {
jdbc.update("""
INSERT INTO attachments
(id, chat_id, owner_id, filename, content_type, size_bytes,
sha256, object_key, staging_key, pipeline_version,
status, error_code, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'queued', NULL, ?, ?)
""", attachment.id(), attachment.chatId(), attachment.ownerId(),
attachment.filename(), attachment.contentType(), attachment.sizeBytes(),
attachment.sha256(), attachment.objectKey(), attachment.stagingKey(),
job.pipelineVersion(),
Timestamp.from(attachment.createdAt()), Timestamp.from(attachment.updatedAt()));
TraceContext traceContext = tracing.capture();
jdbc.update("""
INSERT INTO attachment_jobs
(id, attachment_id, pipeline_version, attempt, status, published,
trace_parent, trace_state, created_at, updated_at)
VALUES (?, ?, ?, ?, 'queued', false, ?, ?, ?, ?)
""", job.jobId(), job.attachmentId(), job.pipelineVersion(), job.attempt(),
traceContext.traceparent(), traceContext.tracestate(),
Timestamp.from(job.createdAt()), Timestamp.from(job.createdAt()));
return attachment;
}
@Override
public Optional<Attachment> findById(UUID id) {
return jdbc.query("SELECT " + COLUMNS + " FROM attachments WHERE id = ?",
(rs, rowNum) -> map(rs), id).stream().findFirst();
}
@Override
public List<Attachment> findAllByIdsInChat(UUID chatId, List<UUID> ids) {
if (ids.isEmpty()) {
return List.of();
}
String placeholders = String.join(",", Collections.nCopies(ids.size(), "?"));
Object[] args = new Object[ids.size() + 1];
args[0] = chatId;
for (int i = 0; i < ids.size(); i++) {
args[i + 1] = ids.get(i);
}
return jdbc.query("SELECT " + COLUMNS + " FROM attachments WHERE chat_id = ? AND id IN ("
+ placeholders + ") AND status <> 'failed'",
(rs, rowNum) -> map(rs), args);
}
@Override
public Set<String> findAllObjectKeys() {
Set<String> keys = new HashSet<>(jdbc.query(
"SELECT object_key FROM attachments WHERE status = 'ready'",
(rs, rowNum) -> rs.getString("object_key")));
keys.addAll(jdbc.query("SELECT object_key FROM attachment_variants",
(rs, rowNum) -> rs.getString("object_key")));
return keys;
}
@Override
public Set<String> findActiveStagingKeys() {
return new HashSet<>(jdbc.query("""
SELECT staging_key
FROM attachments
WHERE status IN ('queued', 'processing') AND staging_key IS NOT NULL
""", (rs, rowNum) -> rs.getString("staging_key")));
}
@Override
public void markPublished(UUID jobId) {
jdbc.update("""
UPDATE attachment_jobs
SET published = true, updated_at = clock_timestamp()
WHERE id = ? AND status = 'queued'
""", jobId);
}
@Override
public boolean markPublishFaultInjected(UUID jobId) {
return jdbc.update("""
UPDATE attachment_jobs
SET publish_fault_injected = true, updated_at = clock_timestamp()
WHERE id = ? AND publish_fault_injected = false AND status = 'queued'
""", jobId) == 1;
}
@Override
public List<AttachmentJob> findUnpublishedJobs(int limit) {
return jdbc.query("""
SELECT id, attachment_id, pipeline_version, attempt, created_at
FROM attachment_jobs
WHERE status = 'queued' AND published = false
AND next_attempt_at <= clock_timestamp()
ORDER BY next_attempt_at, created_at, id
LIMIT ?
""", (rs, rowNum) -> mapJob(rs), limit);
}
@Override
public Optional<TraceContext> findTraceContext(UUID jobId) {
return jdbc.query("""
SELECT trace_parent, trace_state
FROM attachment_jobs
WHERE id = ? AND trace_parent IS NOT NULL
""", (rs, rowNum) -> new TraceContext(
rs.getString("trace_parent"), rs.getString("trace_state")), jobId)
.stream().findFirst();
}
@Override
public int currentAttempt(UUID jobId) {
Integer attempt = jdbc.query("SELECT attempt FROM attachment_jobs WHERE id = ?",
(rs, rowNum) -> rs.getInt("attempt"), jobId).stream().findFirst().orElse(null);
return attempt == null ? 1 : attempt;
}
@Override
public boolean claim(UUID jobId, UUID attachmentId, int pipelineVersion, int attempt,
UUID leaseToken, Duration leaseDuration) {
int claimed = jdbc.update("""
UPDATE attachment_jobs
SET status = 'processing', attempt = GREATEST(attempt, ?),
lease_token = ?,
lease_until = clock_timestamp() + (? * interval '1 millisecond'),
updated_at = clock_timestamp()
WHERE id = ? AND attachment_id = ?
AND pipeline_version = ?
AND (status = 'queued'
OR (status = 'processing' AND lease_until < clock_timestamp()))
AND EXISTS (
SELECT 1 FROM attachments a
WHERE a.id = ? AND a.pipeline_version = ?
AND a.status IN ('queued', 'processing'))
""", attempt, leaseToken, leaseDuration.toMillis(), jobId, attachmentId,
pipelineVersion, attachmentId, pipelineVersion);
if (claimed == 0) {
return false;
}
jdbc.update("""
UPDATE attachments
SET status = 'processing', error_code = NULL, updated_at = clock_timestamp()
WHERE id = ? AND pipeline_version = ?
AND status IN ('queued', 'processing')
""", attachmentId, pipelineVersion);
return true;
}
@Override
public boolean markBeforeEffectFaultInjected(UUID jobId, UUID leaseToken) {
return jdbc.update("""
UPDATE attachment_jobs
SET before_effect_fault_injected = true, updated_at = clock_timestamp()
WHERE id = ? AND status = 'processing' AND lease_token = ?
AND before_effect_fault_injected = false
""", jobId, leaseToken) == 1;
}
@Override
public boolean markAfterEffectFaultInjected(UUID jobId, UUID leaseToken) {
return jdbc.update("""
UPDATE attachment_jobs
SET after_effect_fault_injected = true, updated_at = clock_timestamp()
WHERE id = ? AND status = 'processing' AND lease_token = ?
AND after_effect_fault_injected = false
""", jobId, leaseToken) == 1;
}
@Override
public boolean markQueuedForRetry(UUID jobId, UUID attachmentId, int pipelineVersion,
UUID leaseToken,
int nextAttempt, String errorCode, Instant nextAttemptAt) {
TraceContext traceContext = tracing.capture();
int updated = jdbc.update("""
UPDATE attachment_jobs
SET status = 'queued', attempt = ?, published = false,
last_error_code = ?, next_attempt_at = ?,
trace_parent = ?, trace_state = ?,
lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp()
WHERE id = ? AND attachment_id = ? AND status = 'processing'
AND pipeline_version = ? AND lease_token = ?
""", nextAttempt, errorCode, Timestamp.from(nextAttemptAt),
traceContext.traceparent(), traceContext.tracestate(),
jobId, attachmentId, pipelineVersion, leaseToken);
if (updated == 0) {
return false;
}
jdbc.update("""
UPDATE attachments
SET status = 'queued', error_code = NULL, updated_at = clock_timestamp()
WHERE id = ? AND pipeline_version = ?
AND status IN ('queued', 'processing')
""", attachmentId, pipelineVersion);
return true;
}
@Override
public CompletionResult markReady(UUID jobId, UUID attachmentId, UUID leaseToken, int pipelineVersion,
List<AttachmentVariant> variants, boolean injectCrashAfterCommit) {
boolean triggerCrash = injectCrashAfterCommit && Boolean.TRUE.equals(jdbc.query("""
SELECT NOT result_fault_injected
FROM attachment_jobs
WHERE id = ? AND attachment_id = ? AND status = 'processing' AND lease_token = ?
FOR UPDATE
""", (rs, rowNum) -> rs.getBoolean(1), jobId, attachmentId, leaseToken)
.stream().findFirst().orElse(false));
int completed = jdbc.update("""
UPDATE attachment_jobs
SET status = 'ready', published = true, last_error_code = NULL,
lease_token = NULL, lease_until = NULL,
result_fault_injected = result_fault_injected OR ?,
updated_at = clock_timestamp()
WHERE id = ? AND attachment_id = ? AND status = 'processing'
AND pipeline_version = ? AND lease_token = ?
AND EXISTS (
SELECT 1 FROM attachments a
WHERE a.id = ? AND a.pipeline_version = ?
AND a.status = 'processing')
""", triggerCrash, jobId, attachmentId, pipelineVersion, leaseToken,
attachmentId, pipelineVersion);
if (completed == 0) {
return new CompletionResult(false, false);
}
for (AttachmentVariant variant : variants) {
jdbc.update("""
INSERT INTO attachment_variants
(attachment_id, pipeline_version, name, content_type, size_bytes,
width, height, sha256, object_key, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, clock_timestamp())
ON CONFLICT (attachment_id, pipeline_version, name) DO NOTHING
""", attachmentId, pipelineVersion, variant.name(), variant.contentType(),
variant.sizeBytes(), variant.width(), variant.height(), variant.sha256(),
variant.objectKey());
}
jdbc.update("""
UPDATE attachments
SET status = 'ready', error_code = NULL, updated_at = clock_timestamp()
WHERE id = ? AND pipeline_version = ? AND status = 'processing'
""", attachmentId, pipelineVersion);
return new CompletionResult(true, triggerCrash);
}
@Override
public boolean markFailed(UUID jobId, UUID attachmentId, int pipelineVersion,
UUID leaseToken, String errorCode) {
int updated = jdbc.update("""
UPDATE attachment_jobs
SET status = 'failed', published = true, last_error_code = ?,
lease_token = NULL, lease_until = NULL,
updated_at = clock_timestamp()
WHERE id = ? AND attachment_id = ? AND status = 'processing'
AND pipeline_version = ? AND lease_token = ?
AND EXISTS (SELECT 1 FROM attachments a
WHERE a.id = ? AND a.pipeline_version = ?)
""", errorCode, jobId, attachmentId, pipelineVersion, leaseToken,
attachmentId, pipelineVersion);
if (updated == 0) {
return false;
}
jdbc.update("""
UPDATE attachments
SET status = 'failed', error_code = ?, updated_at = clock_timestamp()
WHERE id = ? AND pipeline_version = ? AND status <> 'ready'
""", errorCode, attachmentId, pipelineVersion);
return true;
}
@Override
public List<AttachmentJob> findExpiredJobs(int limit) {
return jdbc.query("""
SELECT id, attachment_id, pipeline_version, attempt, created_at
FROM attachment_jobs
WHERE status = 'processing' AND lease_until < clock_timestamp()
ORDER BY lease_until, id
LIMIT ?
""", (rs, rowNum) -> mapJob(rs), limit);
}
@Override
public boolean requeueExpired(UUID jobId, UUID attachmentId, int pipelineVersion,
int nextAttempt,
String errorCode, Instant nextAttemptAt) {
int updated = jdbc.update("""
UPDATE attachment_jobs
SET status = 'queued', attempt = ?, published = false,
last_error_code = ?, next_attempt_at = ?,
lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp()
WHERE id = ? AND attachment_id = ? AND status = 'processing'
AND pipeline_version = ? AND lease_until < clock_timestamp()
AND EXISTS (SELECT 1 FROM attachments a
WHERE a.id = ? AND a.pipeline_version = ?)
""", nextAttempt, errorCode, Timestamp.from(nextAttemptAt), jobId, attachmentId,
pipelineVersion, attachmentId, pipelineVersion);
if (updated == 1) {
jdbc.update("""
UPDATE attachments SET status = 'queued', error_code = NULL,
updated_at = clock_timestamp()
WHERE id = ? AND pipeline_version = ? AND status = 'processing'
""", attachmentId, pipelineVersion);
}
return updated == 1;
}
@Override
public boolean failExpired(UUID jobId, UUID attachmentId, int pipelineVersion,
String errorCode) {
int updated = jdbc.update("""
UPDATE attachment_jobs
SET status = 'failed', published = true, last_error_code = ?,
lease_token = NULL, lease_until = NULL, updated_at = clock_timestamp()
WHERE id = ? AND attachment_id = ? AND status = 'processing'
AND pipeline_version = ? AND lease_until < clock_timestamp()
AND EXISTS (SELECT 1 FROM attachments a
WHERE a.id = ? AND a.pipeline_version = ?)
""", errorCode, jobId, attachmentId, pipelineVersion,
attachmentId, pipelineVersion);
if (updated == 1) {
jdbc.update("""
UPDATE attachments SET status = 'failed', error_code = ?,
updated_at = clock_timestamp()
WHERE id = ? AND pipeline_version = ? AND status <> 'ready'
""", errorCode, attachmentId, pipelineVersion);
}
return updated == 1;
}
private Attachment map(ResultSet rs) throws SQLException {
UUID id = rs.getObject("id", UUID.class);
return new Attachment(
id,
rs.getObject("chat_id", UUID.class),
rs.getObject("owner_id", UUID.class),
rs.getString("filename"),
rs.getString("content_type"),
rs.getLong("size_bytes"),
rs.getString("sha256"),
rs.getString("object_key"),
rs.getString("staging_key"),
rs.getString("status"),
findVariants(id),
rs.getString("error_code"),
rs.getTimestamp("created_at").toInstant(),
rs.getTimestamp("updated_at").toInstant());
}
private List<AttachmentVariant> findVariants(UUID attachmentId) {
return jdbc.query("""
SELECT name, content_type, size_bytes, width, height, sha256, object_key
FROM attachment_variants
WHERE attachment_id = ?
AND pipeline_version = (
SELECT pipeline_version FROM attachments WHERE id = ?)
ORDER BY name
""", (rs, rowNum) -> new AttachmentVariant(
rs.getString("name"), rs.getString("content_type"), rs.getLong("size_bytes"),
rs.getInt("width"), rs.getInt("height"), rs.getString("sha256"),
rs.getString("object_key")), attachmentId, attachmentId);
}
private static AttachmentJob mapJob(ResultSet rs) throws SQLException {
return new AttachmentJob(
AttachmentJob.SCHEMA_VERSION,
rs.getObject("id", UUID.class),
AttachmentJob.TYPE,
rs.getObject("attachment_id", UUID.class),
rs.getInt("pipeline_version"),
rs.getInt("attempt"),
rs.getTimestamp("created_at").toInstant());
}
}
@@ -0,0 +1,106 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Chat;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Repository
public class PostgresChatRepository implements ChatRepository {
private final JdbcTemplate jdbc;
public PostgresChatRepository(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Override
@Transactional(timeout = 5)
public Chat save(Chat chat) {
jdbc.update("""
INSERT INTO chats (id, title, created_at)
VALUES (?, ?, ?)
""", chat.id(), chat.title(), Timestamp.from(chat.createdAt()));
for (UUID memberId : chat.memberIds()) {
jdbc.update("""
INSERT INTO chat_members (chat_id, user_id)
VALUES (?, ?)
""", chat.id(), memberId);
}
return chat;
}
@Override
public Optional<Chat> findById(UUID id) {
return jdbc.query("""
SELECT id, title, created_at
FROM chats
WHERE id = ?
""", (rs, rowNum) -> new ChatRow(
rs.getObject("id", UUID.class),
rs.getString("title"),
rs.getTimestamp("created_at").toInstant()), id)
.stream().findFirst()
.map(this::toChat);
}
@Override
public boolean isMember(UUID chatId, UUID userId) {
return Boolean.TRUE.equals(jdbc.queryForObject("""
SELECT EXISTS (
SELECT 1 FROM chat_members
WHERE chat_id = ? AND user_id = ?
)
""", Boolean.class, chatId, userId));
}
@Override
public List<Chat> findAllForUser(UUID userId) {
return findPageForUser(userId, null, null, Integer.MAX_VALUE);
}
@Override
public List<Chat> findPageForUser(UUID userId, UUID afterId, Instant afterCreatedAt, int limitPlusOne) {
StringBuilder sql = new StringBuilder("""
SELECT c.id, c.title, c.created_at
FROM chats c
JOIN chat_members cm ON cm.chat_id = c.id
WHERE cm.user_id = ?
""");
List<Object> parameters = new ArrayList<>();
parameters.add(userId);
if (afterCreatedAt != null) {
sql.append(" AND (c.created_at, c.id) > (?, ?) ");
parameters.add(Timestamp.from(afterCreatedAt));
parameters.add(afterId);
}
sql.append(" ORDER BY c.created_at, c.id LIMIT ? ");
parameters.add(limitPlusOne);
return jdbc.query(sql.toString(), (rs, rowNum) -> new ChatRow(
rs.getObject("id", UUID.class),
rs.getString("title"),
rs.getTimestamp("created_at").toInstant()), parameters.toArray())
.stream().map(this::toChat).toList();
}
private Chat toChat(ChatRow row) {
List<UUID> members = jdbc.queryForList("""
SELECT user_id
FROM chat_members
WHERE chat_id = ?
ORDER BY joined_at, user_id
""", UUID.class, row.id());
return new Chat(row.id(), row.title(), members, row.createdAt());
}
private record ChatRow(UUID id, String title, Instant createdAt) {}
}
@@ -0,0 +1,172 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Message;
import com.example.mtusi_messenger.model.IdempotentMessage;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import java.sql.PreparedStatement;
import java.sql.SQLException;
@Repository
public class PostgresMessageRepository implements MessageRepository {
private final JdbcTemplate jdbc;
public PostgresMessageRepository(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Override
public Message save(Message message) {
jdbc.update("""
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
VALUES (?, ?, ?, ?, ?)
""", message.id(), message.chatId(), message.senderId(), message.text(),
Timestamp.from(message.createdAt()));
if (!message.attachmentIds().isEmpty()) {
jdbc.batchUpdate("""
INSERT INTO message_attachments
(message_id, chat_id, attachment_id, position)
VALUES (?, ?, ?, ?)
""", new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement statement, int index) throws SQLException {
statement.setObject(1, message.id());
statement.setObject(2, message.chatId());
statement.setObject(3, message.attachmentIds().get(index));
statement.setInt(4, index);
}
@Override
public int getBatchSize() {
return message.attachmentIds().size();
}
});
}
return message;
}
@Override
public void lockIdempotencyScope(UUID userId, String method, String path, String key) {
String scope = userId + "\n" + method + "\n" + path + "\n" + key;
jdbc.query(
"SELECT pg_advisory_xact_lock(hashtextextended(?, 0))",
rs -> {
rs.next();
return null;
},
scope);
}
@Override
public void deleteExpiredIdempotency(
UUID userId,
String method,
String path,
String key,
Instant expiresBefore
) {
jdbc.update("""
DELETE FROM message_idempotency
WHERE user_id = ?
AND method = ?
AND request_path = ?
AND idempotency_key = ?
AND created_at < ?
""", userId, method, path, key, Timestamp.from(expiresBefore));
}
@Override
public Optional<IdempotentMessage> findIdempotent(
UUID userId,
String method,
String path,
String key
) {
Optional<IdempotentMessage> result = jdbc.query("""
SELECT i.request_hash,
m.id, m.chat_id, m.sender_id, m.text, m.created_at
FROM message_idempotency i
JOIN messages m ON m.id = i.message_id
WHERE i.user_id = ?
AND i.method = ?
AND i.request_path = ?
AND i.idempotency_key = ?
""", (rs, rowNum) -> new IdempotentMessage(
rs.getBytes("request_hash"),
new Message(
rs.getObject("id", UUID.class),
rs.getObject("chat_id", UUID.class),
rs.getObject("sender_id", UUID.class),
rs.getString("text"),
rs.getTimestamp("created_at").toInstant(),
List.of())),
userId, method, path, key).stream().findFirst();
return result.map(value -> new IdempotentMessage(
value.requestHash(), withAttachments(value.message())));
}
@Override
public void saveIdempotency(
UUID userId,
String method,
String path,
String key,
byte[] requestHash,
UUID messageId,
Instant createdAt
) {
jdbc.update("""
INSERT INTO message_idempotency
(user_id, method, request_path, idempotency_key,
request_hash, message_id, created_at)
VALUES (?, ?, ?, ?, ?, ?, ?)
""", userId, method, path, key, requestHash, messageId,
Timestamp.from(createdAt));
}
@Override
public List<Message> findPage(UUID chatId, Instant afterCreatedAt, UUID afterId, int limitPlusOne) {
StringBuilder sql = new StringBuilder("""
SELECT id, chat_id, sender_id, text, created_at
FROM messages
WHERE chat_id = ?
""");
List<Object> parameters = new ArrayList<>();
parameters.add(chatId);
if (afterCreatedAt != null) {
sql.append(" AND (created_at, id) > (?, ?) ");
parameters.add(Timestamp.from(afterCreatedAt));
parameters.add(afterId);
}
sql.append(" ORDER BY created_at, id LIMIT ? ");
parameters.add(limitPlusOne);
return jdbc.query(sql.toString(), (rs, rowNum) -> new Message(
rs.getObject("id", UUID.class),
rs.getObject("chat_id", UUID.class),
rs.getObject("sender_id", UUID.class),
rs.getString("text"),
rs.getTimestamp("created_at").toInstant(),
List.of()), parameters.toArray()).stream().map(this::withAttachments).toList();
}
private Message withAttachments(Message message) {
List<UUID> attachmentIds = jdbc.query("""
SELECT attachment_id
FROM message_attachments
WHERE message_id = ?
ORDER BY position
""", (rs, rowNum) -> rs.getObject("attachment_id", UUID.class), message.id());
return new Message(message.id(), message.chatId(), message.senderId(), message.text(),
message.createdAt(), attachmentIds);
}
}
@@ -0,0 +1,51 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Session;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.util.Optional;
import java.util.UUID;
@Repository
public class PostgresSessionRepository implements SessionRepository {
private final JdbcTemplate jdbc;
public PostgresSessionRepository(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Override
public Session save(Session session) {
jdbc.update("""
INSERT INTO sessions (id, user_id, token_hash, created_at, expires_at)
VALUES (?, ?, ?, ?, ?)
""", session.id(), session.userId(), session.tokenHash(),
Timestamp.from(session.createdAt()), Timestamp.from(session.expiresAt()));
return session;
}
@Override
public Optional<UUID> findActiveUserId(byte[] tokenHash) {
return jdbc.query("""
SELECT user_id
FROM sessions
WHERE token_hash = ?
AND revoked_at IS NULL
AND expires_at > CURRENT_TIMESTAMP
""", (rs, rowNum) -> rs.getObject("user_id", UUID.class), tokenHash)
.stream().findFirst();
}
@Override
public boolean revoke(byte[] tokenHash) {
return jdbc.update("""
UPDATE sessions
SET revoked_at = CURRENT_TIMESTAMP
WHERE token_hash = ?
AND revoked_at IS NULL
AND expires_at > CURRENT_TIMESTAMP
""", tokenHash) == 1;
}
}
@@ -0,0 +1,72 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.User;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import java.sql.Timestamp;
import java.util.Optional;
import java.util.UUID;
@Repository
public class PostgresUserRepository implements UserRepository {
private final JdbcTemplate jdbc;
public PostgresUserRepository(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
@Override
public User save(User user, String passwordHash) {
jdbc.update("""
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES (?, ?, ?, ?, ?)
""", user.id(), user.username(), user.displayName(), passwordHash,
Timestamp.from(user.createdAt()));
return user;
}
@Override
public Optional<User> findById(UUID id) {
return jdbc.query("""
SELECT id, username, display_name, created_at
FROM users
WHERE id = ?
""", (rs, rowNum) -> new User(
rs.getObject("id", UUID.class),
rs.getString("username"),
rs.getString("display_name"),
rs.getTimestamp("created_at").toInstant()), id)
.stream().findFirst();
}
@Override
public Optional<User> findByUsername(String username) {
return jdbc.query("""
SELECT id, username, display_name, created_at
FROM users
WHERE username = ?
""", (rs, rowNum) -> new User(
rs.getObject("id", UUID.class),
rs.getString("username"),
rs.getString("display_name"),
rs.getTimestamp("created_at").toInstant()), username)
.stream().findFirst();
}
@Override
public Optional<UserCredentials> findCredentialsByUsername(String username) {
return jdbc.query("""
SELECT id, username, display_name, password_hash, created_at
FROM users
WHERE username = ?
""", (rs, rowNum) -> new UserCredentials(
new User(
rs.getObject("id", UUID.class),
rs.getString("username"),
rs.getString("display_name"),
rs.getTimestamp("created_at").toInstant()),
rs.getString("password_hash")), username)
.stream().findFirst();
}
}
@@ -0,0 +1,12 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.Session;
import java.util.Optional;
import java.util.UUID;
public interface SessionRepository {
Session save(Session session);
Optional<UUID> findActiveUserId(byte[] tokenHash);
boolean revoke(byte[] tokenHash);
}
@@ -0,0 +1,14 @@
package com.example.mtusi_messenger.repository;
import com.example.mtusi_messenger.model.User;
import java.util.Optional;
import java.util.UUID;
public interface UserRepository {
User save(User user, String passwordHash);
Optional<User> findById(UUID id);
Optional<User> findByUsername(String username);
Optional<UserCredentials> findCredentialsByUsername(String username);
record UserCredentials(User user, String passwordHash) {}
}
@@ -0,0 +1,130 @@
package com.example.mtusi_messenger.security;
import com.example.mtusi_messenger.service.AuthenticationService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Enumeration;
import java.util.List;
public class ApiAuthenticationFilter extends OncePerRequestFilter {
private static final String AUTHORIZATION = "Authorization";
private static final String SESSION_PATH = "/api/v1/auth/sessions";
private final AuthenticationManager authenticationManager;
private final AuthenticationService sessions;
private final RestAuthenticationEntryPoint basicEntryPoint;
private final RestAuthenticationEntryPoint bearerEntryPoint;
public ApiAuthenticationFilter(
AuthenticationManager authenticationManager,
AuthenticationService sessions,
RestAuthenticationEntryPoint basicEntryPoint,
RestAuthenticationEntryPoint bearerEntryPoint
) {
this.authenticationManager = authenticationManager;
this.sessions = sessions;
this.basicEntryPoint = basicEntryPoint;
this.bearerEntryPoint = bearerEntryPoint;
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain
) throws ServletException, IOException {
boolean basicLogin = HttpMethod.POST.matches(request.getMethod())
&& SESSION_PATH.equals(request.getRequestURI());
if (isPublicRequest(request) && !basicLogin) {
filterChain.doFilter(request, response);
return;
}
try {
Authentication authentication = basicLogin
? authenticateBasic(request)
: authenticateBearer(request);
var context = SecurityContextHolder.createEmptyContext();
context.setAuthentication(authentication);
SecurityContextHolder.setContext(context);
filterChain.doFilter(request, response);
} catch (AuthenticationException e) {
SecurityContextHolder.clearContext();
(basicLogin ? basicEntryPoint : bearerEntryPoint)
.commence(request, response, e);
} finally {
SecurityContextHolder.clearContext();
}
}
private Authentication authenticateBasic(HttpServletRequest request) {
String header = singleAuthorizationHeader(request);
if (!header.startsWith("Basic ") || header.length() == 6) {
throw new BadCredentialsException("Invalid Basic credentials");
}
try {
byte[] decoded = Base64.getDecoder().decode(header.substring(6));
String credentials = new String(decoded, StandardCharsets.UTF_8);
int separator = credentials.indexOf(':');
if (separator <= 0) {
throw new BadCredentialsException("Invalid Basic credentials");
}
return authenticationManager.authenticate(
UsernamePasswordAuthenticationToken.unauthenticated(
credentials.substring(0, separator),
credentials.substring(separator + 1)));
} catch (IllegalArgumentException e) {
throw new BadCredentialsException("Invalid Basic credentials", e);
}
}
private Authentication authenticateBearer(HttpServletRequest request) {
String header = singleAuthorizationHeader(request);
if (!header.startsWith("Bearer ") || header.length() == 7) {
throw new BadCredentialsException("Invalid Bearer token");
}
String token = header.substring(7);
if (!token.matches("[A-Za-z0-9_-]{43}")) {
throw new BadCredentialsException("Invalid Bearer token");
}
SessionPrincipal principal = sessions.authenticateBearer(token);
return UsernamePasswordAuthenticationToken.authenticated(principal, null, List.of());
}
private String singleAuthorizationHeader(HttpServletRequest request) {
Enumeration<String> values = request.getHeaders(AUTHORIZATION);
if (values == null || !values.hasMoreElements()) {
throw new BadCredentialsException("Authentication required");
}
String value = values.nextElement();
if (values.hasMoreElements()) {
throw new BadCredentialsException("Multiple Authorization headers");
}
return value;
}
private boolean isPublicRequest(HttpServletRequest request) {
String path = request.getRequestURI();
return path.startsWith("/health/")
|| path.equals("/swagger-ui.html")
|| path.startsWith("/swagger-ui/")
|| path.equals("/v3/api-docs")
|| path.startsWith("/v3/api-docs/")
|| (HttpMethod.POST.matches(request.getMethod())
&& "/api/v1/users".equals(path));
}
}
@@ -0,0 +1,63 @@
package com.example.mtusi_messenger.security;
import com.example.mtusi_messenger.repository.UserRepository;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.dao.DataAccessException;
import java.util.List;
@Component
public class DatabaseAuthenticationProvider implements AuthenticationProvider {
private final UserRepository users;
private final PasswordEncoder passwordEncoder;
private final String dummyPasswordHash;
public DatabaseAuthenticationProvider(UserRepository users, PasswordEncoder passwordEncoder) {
this.users = users;
this.passwordEncoder = passwordEncoder;
this.dummyPasswordHash = passwordEncoder.encode("dummy-password-used-only-for-timing");
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = authentication.getName();
String password = String.valueOf(authentication.getCredentials());
final java.util.Optional<UserRepository.UserCredentials> stored;
try {
stored = users.findCredentialsByUsername(username);
} catch (DataAccessException e) {
throw new AuthenticationServiceException("Authentication database is unavailable", e);
}
String passwordHash = stored.map(UserRepository.UserCredentials::passwordHash)
.filter(hash -> hash.startsWith("$argon2"))
.orElse(dummyPasswordHash);
boolean matches;
try {
matches = passwordEncoder.matches(password, passwordHash);
} catch (IllegalArgumentException e) {
matches = false;
}
if (stored.isEmpty() || !matches) {
throw new BadCredentialsException("Invalid credentials");
}
return UsernamePasswordAuthenticationToken.authenticated(
stored.get().user(),
null,
List.of());
}
@Override
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
}
@@ -0,0 +1,46 @@
package com.example.mtusi_messenger.security;
import com.example.mtusi_messenger.dto.ErrorResponse;
import com.example.mtusi_messenger.web.RequestIdFilter;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.web.AuthenticationEntryPoint;
import java.io.IOException;
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
private final ObjectMapper mapper;
private final String challenge;
public RestAuthenticationEntryPoint(ObjectMapper mapper, String challenge) {
this.mapper = mapper;
this.challenge = challenge;
}
@Override
public void commence(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException exception
) throws IOException {
String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE);
boolean unavailable = exception instanceof AuthenticationServiceException;
response.setStatus(unavailable
? HttpServletResponse.SC_SERVICE_UNAVAILABLE
: HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
if (!unavailable) {
response.setHeader("WWW-Authenticate", challenge);
}
mapper.writeValue(response.getOutputStream(), new ErrorResponse(
new ErrorResponse.ErrorBody(
unavailable ? "unavailable" : "unauthorized",
unavailable ? "Authentication service temporarily unavailable" : "Authentication required",
requestId)));
}
}
@@ -0,0 +1,14 @@
package com.example.mtusi_messenger.security;
import com.example.mtusi_messenger.model.User;
public record SessionPrincipal(User user, byte[] tokenHash) {
public SessionPrincipal {
tokenHash = tokenHash.clone();
}
@Override
public byte[] tokenHash() {
return tokenHash.clone();
}
}
@@ -0,0 +1,106 @@
package com.example.mtusi_messenger.service;
import com.example.mtusi_messenger.repository.AttachmentRepository;
import com.example.mtusi_messenger.storage.ObjectStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.util.HashSet;
import java.util.Set;
@Component
@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true)
public class AttachmentReconciler {
private static final Logger log = LoggerFactory.getLogger(AttachmentReconciler.class);
private static final String PREFIX = "attachments/";
private final AttachmentRepository attachments;
private final ObjectStorage storage;
private final Duration gracePeriod;
private final boolean dryRun;
private final Clock clock;
@Autowired
public AttachmentReconciler(
AttachmentRepository attachments,
ObjectStorage storage,
@Value("${messenger.attachments.cleanup-grace-seconds:3600}") long graceSeconds,
@Value("${messenger.attachments.cleanup-dry-run:false}") boolean dryRun
) {
this(attachments, storage, Duration.ofSeconds(graceSeconds), dryRun, Clock.systemUTC());
}
AttachmentReconciler(AttachmentRepository attachments,
ObjectStorage storage,
Duration gracePeriod,
boolean dryRun,
Clock clock) {
if (gracePeriod.isNegative() || gracePeriod.isZero()) {
throw new IllegalArgumentException("Attachment cleanup grace period must be positive");
}
this.attachments = attachments;
this.storage = storage;
this.gracePeriod = gracePeriod;
this.dryRun = dryRun;
this.clock = clock;
}
@Scheduled(
fixedDelayString = "${messenger.attachments.reconcile-interval-millis:600000}",
initialDelayString = "${messenger.attachments.reconcile-initial-delay-millis:60000}")
public void scheduledReconcile() {
try {
Report report = reconcile();
if (report.orphanObjects() > 0 || report.missingObjects() > 0) {
log.warn("Attachment reconciliation: {} orphan, {} deleted, {} missing, dryRun={}",
report.orphanObjects(), report.deletedObjects(), report.missingObjects(), dryRun);
}
} catch (RuntimeException error) {
log.warn("Attachment reconciliation postponed: {}", error.getMessage());
}
}
public Report reconcile() {
Set<String> databaseKeys = attachments.findAllObjectKeys();
var storedObjects = storage.list(PREFIX);
Set<String> storageKeys = new HashSet<>();
Instant deleteBefore = clock.instant().minus(gracePeriod);
int orphans = 0;
int deleted = 0;
for (ObjectStorage.StoredObject object : storedObjects) {
storageKeys.add(object.objectKey());
if (!databaseKeys.contains(object.objectKey()) && object.lastModified().isBefore(deleteBefore)) {
orphans++;
if (!dryRun) {
storage.delete(object.objectKey());
deleted++;
}
}
}
int missing = 0;
for (String databaseKey : databaseKeys) {
if (!storageKeys.contains(databaseKey)) {
missing++;
log.error("Attachment metadata references missing object {}", databaseKey);
}
}
return new Report(databaseKeys.size(), storedObjects.size(), orphans, deleted, missing, dryRun);
}
public record Report(int metadataObjects,
int storageObjects,
int orphanObjects,
int deletedObjects,
int missingObjects,
boolean dryRun) {
}
}
@@ -0,0 +1,295 @@
package com.example.mtusi_messenger.service;
import com.example.mtusi_messenger.exception.ApiExceptions;
import com.example.mtusi_messenger.model.Attachment;
import com.example.mtusi_messenger.model.AttachmentJob;
import com.example.mtusi_messenger.model.AttachmentVariant;
import com.example.mtusi_messenger.queue.AttachmentJobPublisher;
import com.example.mtusi_messenger.repository.AttachmentRepository;
import com.example.mtusi_messenger.storage.ObjectStorage;
import com.example.mtusi_messenger.storage.ObjectStorageException;
import com.github.f4b6a3.uuid.UuidCreator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HexFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
@Service
public class AttachmentService {
private static final List<String> ALLOWED_TYPES = List.of("image/png", "image/jpeg");
private final AttachmentRepository attachments;
private final ChatService chats;
private final ObjectStorage storage;
private final AttachmentJobPublisher publisher;
private final TransactionTemplate transaction;
private final long maxUploadBytes;
private final long maxImagePixels;
private final Semaphore uploadPermits;
private final long uploadPermitWaitMillis;
private final boolean injectCrashAfterOutboxCommit;
private final int pipelineVersion;
public AttachmentService(
AttachmentRepository attachments,
ChatService chats,
ObjectStorage storage,
AttachmentJobPublisher publisher,
TransactionTemplate transaction,
@Value("${messenger.attachments.max-upload-bytes:10485760}") long maxUploadBytes,
@Value("${messenger.attachments.max-image-pixels:40000000}") long maxImagePixels,
@Value("${messenger.attachments.max-concurrent-uploads:3}") int maxConcurrentUploads,
@Value("${messenger.attachments.upload-permit-wait-millis:10000}") long uploadPermitWaitMillis,
@Value("${messenger.jobs.fault-crash-after-outbox-commit:false}") boolean injectCrashAfterOutboxCommit,
@Value("${messenger.jobs.pipeline-version:2}") int pipelineVersion
) {
this.attachments = attachments;
this.chats = chats;
this.storage = storage;
this.publisher = publisher;
this.transaction = transaction;
this.maxUploadBytes = maxUploadBytes;
this.maxImagePixels = maxImagePixels;
if (maxConcurrentUploads < 1 || uploadPermitWaitMillis < 1) {
throw new IllegalArgumentException("Upload concurrency limits must be positive");
}
this.uploadPermits = new Semaphore(maxConcurrentUploads, true);
this.uploadPermitWaitMillis = uploadPermitWaitMillis;
this.injectCrashAfterOutboxCommit = injectCrashAfterOutboxCommit;
if (pipelineVersion < AttachmentJob.MIN_PIPELINE_VERSION
|| pipelineVersion > AttachmentJob.CURRENT_PIPELINE_VERSION) {
throw new IllegalArgumentException("Unsupported attachment pipeline version");
}
this.pipelineVersion = pipelineVersion;
}
public Attachment upload(UUID chatId,
UUID ownerId,
String filename,
String declaredContentType,
long declaredLength,
InputStream input) {
chats.getAccessible(chatId, ownerId);
String safeFilename = validateFilename(filename);
String contentType = normalizeContentType(declaredContentType);
if (declaredLength > maxUploadBytes) {
throw ApiExceptions.payloadTooLarge("Attachment exceeds 10 MiB");
}
try {
try {
if (!uploadPermits.tryAcquire(uploadPermitWaitMillis, TimeUnit.MILLISECONDS)) {
throw ApiExceptions.tooManyRequests("Upload capacity is temporarily exhausted");
}
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw ApiExceptions.unavailable("Upload was interrupted");
}
try {
return storeValidated(chatId, ownerId, safeFilename, contentType, input);
} finally {
uploadPermits.release();
}
} catch (com.example.mtusi_messenger.exception.ApiException error) {
throw error;
}
}
private Attachment storeValidated(UUID chatId,
UUID ownerId,
String safeFilename,
String contentType,
InputStream input) {
byte[] bytes = readBounded(input);
if (bytes.length == 0) {
throw ApiExceptions.unsupportedMediaType("Image is empty");
}
validateImage(bytes, contentType);
UUID id = UuidCreator.getTimeOrderedEpochPlus1();
String objectKey = "attachments/" + id + "/original";
String stagingKey = "staging/" + id + "/original";
Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS);
AttachmentJob job = AttachmentJob.first(UUID.randomUUID(), id, pipelineVersion, now);
Attachment attachment = new Attachment(id, chatId, ownerId, safeFilename, contentType,
bytes.length, sha256(bytes), objectKey, stagingKey, "queued", List.of(),
null, now, now);
storage.put(stagingKey, bytes, contentType);
try {
Attachment saved = transaction.execute(status -> attachments.saveQueued(attachment, job));
if (injectCrashAfterOutboxCommit && attachments.markPublishFaultInjected(job.jobId())) {
// Opt-in fault injection for the exact DB COMMIT -> broker publish window.
// The persisted outbox row remains unpublished and is recovered after restart.
Runtime.getRuntime().halt(87);
}
try {
publisher.publish(job);
attachments.markPublished(job.jobId());
return saved;
} catch (RuntimeException publishFailure) {
// The database job and staging object are intentionally retained.
// The scheduled republisher closes the DB-commit -> broker window.
throw ApiExceptions.unavailable("Attachment was staged; queue publication is pending");
}
} catch (RuntimeException databaseFailure) {
if (databaseFailure instanceof com.example.mtusi_messenger.exception.ApiException) {
throw databaseFailure;
}
try {
storage.delete(stagingKey);
} catch (RuntimeException cleanupFailure) {
databaseFailure.addSuppressed(cleanupFailure);
}
throw databaseFailure;
}
}
public Attachment getAccessible(UUID attachmentId, UUID userId) {
Attachment attachment = attachments.findById(attachmentId)
.orElseThrow(() -> ApiExceptions.notFound("Attachment not found"));
chats.getAccessible(attachment.chatId(), userId);
return attachment;
}
public Download download(UUID attachmentId, UUID userId) {
return download(attachmentId, userId, "original");
}
public Download download(UUID attachmentId, UUID userId, String variantName) {
Attachment attachment = getAccessible(attachmentId, userId);
if (!"ready".equals(attachment.status())) {
throw ApiExceptions.conflict("Attachment content is not ready");
}
if ("original".equals(variantName)) {
return new Download(attachment, attachment.contentType(), attachment.filename(),
storage.get(attachment.objectKey()));
}
if (!List.of("thumbnail", "crop", "optimized").contains(variantName)) {
throw ApiExceptions.invalid("Unsupported attachment variant");
}
AttachmentVariant variant = attachment.variants().stream()
.filter(candidate -> candidate.name().equals(variantName))
.findFirst()
.orElseThrow(() -> ApiExceptions.notFound("Attachment variant not found"));
String extension = "image/webp".equals(variant.contentType()) ? ".webp" : ".jpg";
return new Download(attachment, variant.contentType(), variantName + extension,
storage.get(variant.objectKey()));
}
public void validateForMessage(UUID chatId, List<UUID> attachmentIds) {
if (attachmentIds.isEmpty()) {
return;
}
if (attachments.findAllByIdsInChat(chatId, attachmentIds).size() != attachmentIds.size()) {
throw ApiExceptions.notFound("Attachment not found");
}
}
private byte[] readBounded(InputStream input) {
try {
ByteArrayOutputStream output = new ByteArrayOutputStream(
(int) Math.min(maxUploadBytes, 1024 * 1024));
byte[] chunk = new byte[8192];
long total = 0;
int read;
while ((read = input.read(chunk)) != -1) {
total += read;
if (total > maxUploadBytes) {
throw ApiExceptions.payloadTooLarge("Attachment exceeds 10 MiB");
}
output.write(chunk, 0, read);
}
return output.toByteArray();
} catch (IOException error) {
throw ApiExceptions.invalid("Cannot read request body");
}
}
private void validateImage(byte[] bytes, String declaredContentType) {
ImageIO.setUseCache(false);
try (var imageInput = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes))) {
if (imageInput == null) {
throw ApiExceptions.unsupportedMediaType("Invalid image");
}
Iterator<ImageReader> readers = ImageIO.getImageReaders(imageInput);
if (!readers.hasNext()) {
throw ApiExceptions.unsupportedMediaType("Invalid PNG/JPEG image");
}
ImageReader reader = readers.next();
try {
reader.setInput(imageInput, true, true);
String actualType = switch (reader.getFormatName().toLowerCase(Locale.ROOT)) {
case "png" -> "image/png";
case "jpeg", "jpg" -> "image/jpeg";
default -> throw ApiExceptions.unsupportedMediaType("Only PNG and JPEG are supported");
};
if (!actualType.equals(declaredContentType)) {
throw ApiExceptions.unsupportedMediaType("Content-Type does not match image bytes");
}
int width = reader.getWidth(0);
int height = reader.getHeight(0);
if (width <= 0 || height <= 0) {
throw ApiExceptions.unsupportedMediaType("Invalid image dimensions");
}
if ((long) width * height > maxImagePixels) {
throw ApiExceptions.payloadTooLarge("Image exceeds 40 million pixels");
}
if (reader.read(0) == null) {
throw ApiExceptions.unsupportedMediaType("Image cannot be decoded");
}
} finally {
reader.dispose();
}
} catch (com.example.mtusi_messenger.exception.ApiException error) {
throw error;
} catch (IOException | RuntimeException error) {
throw ApiExceptions.unsupportedMediaType("Corrupted PNG/JPEG image");
}
}
private static String validateFilename(String filename) {
if (filename == null || filename.isBlank() || filename.length() > 255
|| filename.equals(".") || filename.equals("..")
|| filename.indexOf('/') >= 0 || filename.indexOf('\\') >= 0
|| filename.codePoints().anyMatch(Character::isISOControl)) {
throw ApiExceptions.invalid("Invalid filename");
}
return filename;
}
private static String normalizeContentType(String contentType) {
String normalized = contentType == null ? "" : contentType.split(";", 2)[0].trim().toLowerCase(Locale.ROOT);
if (!ALLOWED_TYPES.contains(normalized)) {
throw ApiExceptions.unsupportedMediaType("Only image/png and image/jpeg are supported");
}
return normalized;
}
private static String sha256(byte[] bytes) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
} catch (NoSuchAlgorithmException impossible) {
throw new IllegalStateException("SHA-256 is unavailable", impossible);
}
}
public record Download(Attachment attachment, String contentType, String filename, byte[] bytes) {
}
}
@@ -0,0 +1,104 @@
package com.example.mtusi_messenger.service;
import com.example.mtusi_messenger.cache.UserCache;
import com.example.mtusi_messenger.model.Session;
import com.example.mtusi_messenger.model.User;
import com.example.mtusi_messenger.repository.SessionRepository;
import com.example.mtusi_messenger.repository.UserRepository;
import com.example.mtusi_messenger.security.SessionPrincipal;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Base64;
import java.util.UUID;
@Service
public class AuthenticationService {
private static final SecureRandom SECURE_RANDOM = new SecureRandom();
private final UserRepository users;
private final SessionRepository sessions;
private final UserCache userCache;
private final long ttlSeconds;
public AuthenticationService(
UserRepository users,
SessionRepository sessions,
UserCache userCache,
@Value("${messenger.session.ttl-seconds:3600}") long ttlSeconds
) {
if (ttlSeconds <= 0) {
throw new IllegalArgumentException("Session TTL must be positive");
}
this.users = users;
this.sessions = sessions;
this.userCache = userCache;
this.ttlSeconds = ttlSeconds;
}
public IssuedSession issueSession(User user) {
String token = newToken();
Instant createdAt = Instant.now().truncatedTo(ChronoUnit.MICROS);
Instant expiresAt = createdAt.plusSeconds(ttlSeconds);
sessions.save(new Session(
UUID.randomUUID(),
user.id(),
hashToken(token),
createdAt,
expiresAt));
return new IssuedSession(token, expiresAt, user);
}
public SessionPrincipal authenticateBearer(String token) {
byte[] tokenHash = hashToken(token);
try {
UUID userId = sessions.findActiveUserId(tokenHash)
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
User user = userCache.find(userId).orElseGet(() -> {
User loaded = users.findById(userId)
.orElseThrow(() -> new BadCredentialsException("Invalid or expired session"));
userCache.put(loaded);
return loaded;
});
return new SessionPrincipal(user, tokenHash);
} catch (DataAccessException e) {
throw new AuthenticationServiceException("Authentication database is unavailable", e);
}
}
public void revoke(SessionPrincipal principal) {
try {
if (!sessions.revoke(principal.tokenHash())) {
throw new BadCredentialsException("Invalid or expired session");
}
} catch (DataAccessException e) {
throw new AuthenticationServiceException("Authentication database is unavailable", e);
}
}
private String newToken() {
byte[] bytes = new byte[32];
SECURE_RANDOM.nextBytes(bytes);
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
private byte[] hashToken(String token) {
try {
return MessageDigest.getInstance("SHA-256")
.digest(token.getBytes(StandardCharsets.US_ASCII));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 is unavailable", e);
}
}
public record IssuedSession(String token, Instant expiresAt, User user) {}
}
@@ -0,0 +1,38 @@
package com.example.mtusi_messenger.service;
import org.springframework.stereotype.Service;
import com.example.mtusi_messenger.dto.CreateChatRequest;
import com.example.mtusi_messenger.exception.ApiExceptions;
import com.example.mtusi_messenger.model.Chat;
import com.example.mtusi_messenger.repository.ChatRepository;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
@Service
public class ChatService {
private final ChatRepository chats; private final UserService users; private final CursorService cursors;
public ChatService(ChatRepository chats, UserService users, CursorService cursors) { this.chats=chats; this.users=users; this.cursors=cursors; }
public Chat create(CreateChatRequest r, UUID caller) {
Set<UUID> ids = new LinkedHashSet<>(r.member_ids());
if (ids.size() != r.member_ids().size() || !ids.contains(caller)) throw ApiExceptions.invalid("Invalid member_ids");
for (UUID id : ids) if (id == null || !users.exists(id)) throw ApiExceptions.invalid("Invalid member_ids");
return chats.save(new Chat(UUID.randomUUID(), r.title(), List.copyOf(ids),
Instant.now().truncatedTo(ChronoUnit.MICROS)));
}
public Chat getAccessible(UUID chatId, UUID userId) {
users.get(userId);
if (!chats.isMember(chatId, userId)) throw ApiExceptions.notFound("Chat not found");
return chats.findById(chatId).orElseThrow(() -> ApiExceptions.notFound("Chat not found"));
}
public List<Chat> page(UUID userId, int limit, String cursor) {
CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "chats", userId);
return chats.findPageForUser(userId, c == null ? null : c.id(), c == null ? null : c.createdAt(), limit + 1);
}
public String nextCursor(UUID userId,
Chat last,
boolean hasNext
) {
return hasNext ? cursors.encode("chats", userId, last.createdAt(), last.id()) : null;
}
}
@@ -0,0 +1,40 @@
package com.example.mtusi_messenger.service;
import com.example.mtusi_messenger.exception.ApiException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import com.example.mtusi_messenger.exception.ApiExceptions;
import java.time.Instant;
import java.util.Base64;
import java.util.UUID;
@Service
public class CursorService {
private final ObjectMapper mapper;
public CursorService(ObjectMapper mapper) { this.mapper = mapper; }
public String encode(String resource, UUID resourceId, Instant createdAt, UUID id) {
try {
byte[] json = mapper.writeValueAsBytes(new CursorPayload(1, resource, resourceId, createdAt.toString(), id));
return Base64.getUrlEncoder().withoutPadding().encodeToString(json);
} catch (Exception e) { throw new IllegalStateException(e); }
}
public Cursor decode(String raw, String resource, UUID resourceId) {
if (raw == null || raw.isBlank()) throw ApiExceptions.invalid("Invalid cursor");
try {
CursorPayload p = mapper.readValue(Base64.getUrlDecoder().decode(raw), CursorPayload.class);
if (p.v != 1
|| !resource.equals(p.resource)
|| !Objects.equals(resourceId, p.resourceId)
|| p.createdAt() == null
|| p.createdAt().isBlank()
|| p.id() == null
) throw ApiExceptions.invalid("Invalid cursor");
return new Cursor(Instant.parse(p.createdAt), p.id);
} catch (ApiException e) { throw e; }
catch (Exception e) { throw ApiExceptions.invalid("Invalid cursor"); }
}
public record Cursor(Instant createdAt, UUID id) {}
private record CursorPayload(int v, String resource, UUID resourceId, String createdAt, UUID id) {}
private static final class Objects { static boolean equals(Object a, Object b) { return java.util.Objects.equals(a,b); } }
}
@@ -0,0 +1,102 @@
package com.example.mtusi_messenger.service;
import com.github.f4b6a3.uuid.UuidCreator;
import com.example.mtusi_messenger.exception.ApiExceptions;
import com.example.mtusi_messenger.model.IdempotentMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.example.mtusi_messenger.dto.CreateMessageRequest;
import com.example.mtusi_messenger.model.Message;
import com.example.mtusi_messenger.repository.MessageRepository;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
@Service
public class MessageService {
private static final String METHOD = "POST";
private final MessageRepository messages;
private final ChatService chats;
private final CursorService cursors;
private final AttachmentService attachments;
private final Duration idempotencyTtl;
public MessageService(
MessageRepository messages,
ChatService chats,
CursorService cursors,
AttachmentService attachments,
@Value("${messenger.idempotency.ttl-seconds:86400}") long idempotencyTtlSeconds
) {
if (idempotencyTtlSeconds < 86400) {
throw new IllegalArgumentException("Idempotency TTL must be at least 24 hours");
}
this.messages = messages;
this.chats = chats;
this.cursors = cursors;
this.attachments = attachments;
this.idempotencyTtl = Duration.ofSeconds(idempotencyTtlSeconds);
}
@Transactional
public Message create(UUID chatId, UUID senderId, CreateMessageRequest r, String idempotencyKey) {
chats.getAccessible(chatId, senderId);
attachments.validateForMessage(chatId, r.attachment_ids());
String path = "/api/v1/chats/" + chatId + "/messages";
byte[] requestHash = hash(r.text(), r.attachment_ids());
Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS);
// The transaction-scoped PostgreSQL advisory lock serializes the same
// idempotency scope across every API replica. A hash collision only
// causes harmless extra serialization; the full scope is still checked.
messages.lockIdempotencyScope(senderId, METHOD, path, idempotencyKey);
messages.deleteExpiredIdempotency(
senderId, METHOD, path, idempotencyKey, now.minus(idempotencyTtl));
var existing = messages.findIdempotent(senderId, METHOD, path, idempotencyKey);
if (existing.isPresent()) {
IdempotentMessage value = existing.get();
if (!Arrays.equals(value.requestHash(), requestHash)) {
throw ApiExceptions.conflict("Idempotency-Key was already used with another request body");
}
return value.message();
}
Message message = messages.save(new Message(
UuidCreator.getTimeOrderedEpochPlus1(), chatId, senderId, r.text(), now,
r.attachment_ids()));
messages.saveIdempotency(
senderId, METHOD, path, idempotencyKey, requestHash, message.id(), now);
return message;
}
private static byte[] hash(String text, List<UUID> attachmentIds) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] textBytes = text.getBytes(StandardCharsets.UTF_8);
digest.update(java.nio.ByteBuffer.allocate(Integer.BYTES).putInt(textBytes.length).array());
digest.update(textBytes);
for (UUID id : attachmentIds) {
digest.update(java.nio.ByteBuffer.allocate(16)
.putLong(id.getMostSignificantBits())
.putLong(id.getLeastSignificantBits()).array());
}
return digest.digest();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("SHA-256 is unavailable", e);
}
}
public List<Message> page(UUID chatId, UUID userId, int limit, String cursor) {
chats.getAccessible(chatId, userId);
CursorService.Cursor c = cursor == null ? null : cursors.decode(cursor, "messages", chatId);
return messages.findPage(chatId, c == null ? null : c.createdAt(), c == null ? null : c.id(), limit + 1);
}
public String nextCursor(UUID chatId, Message last, boolean hasNext) { return hasNext ? cursors.encode("messages", chatId, last.createdAt(), last.id()) : null; }
}
@@ -0,0 +1,85 @@
package com.example.mtusi_messenger.service;
import org.springframework.boot.availability.ApplicationAvailability;
import org.springframework.boot.availability.AvailabilityChangeEvent;
import org.springframework.boot.availability.ReadinessState;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.concurrent.atomic.AtomicBoolean;
@Service
public class ReadinessService {
private final JdbcTemplate jdbc;
private final StringRedisTemplate redis;
private final ApplicationAvailability availability;
private final ApplicationEventPublisher events;
private final AtomicBoolean dependencyUnavailable = new AtomicBoolean(false);
private final AtomicBoolean shuttingDown = new AtomicBoolean(false);
public ReadinessService(
JdbcTemplate jdbc,
StringRedisTemplate redis,
ApplicationAvailability availability,
ApplicationEventPublisher events
) {
this.jdbc = jdbc;
this.redis = redis;
this.availability = availability;
this.events = events;
}
public boolean probeDependencies() {
try {
// Redis is an optional cache. Ping only warms the lazy connection;
// its failure must not make the authoritative API unavailable.
redis.execute((RedisCallback<String>) connection -> connection.ping());
} catch (DataAccessException ignored) {
// PostgreSQL remains the source of truth.
}
try {
// The schema-level probe proves that both the shared idempotency
// schema (lab3) and the attachment schema (lab4/lab5) completed
// before this replica is allowed to serve business traffic.
jdbc.queryForObject("""
SELECT (SELECT count(*) FROM message_idempotency)
+ (SELECT count(*) FROM attachments)
""", Long.class);
markDependenciesAvailable();
return true;
} catch (DataAccessException e) {
markDependenciesUnavailable();
return false;
}
}
public boolean acceptsBusinessTraffic() {
return !shuttingDown.get()
&& !dependencyUnavailable.get()
&& availability.getReadinessState() == ReadinessState.ACCEPTING_TRAFFIC;
}
@EventListener(ContextClosedEvent.class)
void onContextClosed() {
shuttingDown.set(true);
}
private void markDependenciesUnavailable() {
dependencyUnavailable.set(true);
AvailabilityChangeEvent.publish(events, this, ReadinessState.REFUSING_TRAFFIC);
}
private void markDependenciesAvailable() {
boolean recovered = dependencyUnavailable.getAndSet(false);
if (recovered && !shuttingDown.get()) {
AvailabilityChangeEvent.publish(events, this, ReadinessState.ACCEPTING_TRAFFIC);
}
}
}
@@ -0,0 +1,65 @@
package com.example.mtusi_messenger.service;
import com.example.mtusi_messenger.repository.AttachmentRepository;
import com.example.mtusi_messenger.storage.ObjectStorage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.Clock;
import java.time.Duration;
import java.util.Set;
@Component
@ConditionalOnProperty(name = "messenger.role", havingValue = "api", matchIfMissing = true)
public class StagingCleaner {
private static final Logger log = LoggerFactory.getLogger(StagingCleaner.class);
private static final String PREFIX = "staging/";
private final AttachmentRepository attachments;
private final ObjectStorage storage;
private final Duration retention;
private final Clock clock;
@Autowired
public StagingCleaner(
AttachmentRepository attachments,
ObjectStorage storage,
@Value("${messenger.attachments.staging-retention-seconds:86400}") long retentionSeconds) {
this(attachments, storage, Duration.ofSeconds(retentionSeconds), Clock.systemUTC());
}
StagingCleaner(
AttachmentRepository attachments,
ObjectStorage storage,
Duration retention,
Clock clock) {
if (retention.isZero() || retention.isNegative()) {
throw new IllegalArgumentException("Staging retention must be positive");
}
this.attachments = attachments;
this.storage = storage;
this.retention = retention;
this.clock = clock;
}
@Scheduled(
fixedDelayString = "${messenger.attachments.reconcile-interval-millis:600000}",
initialDelayString = "${messenger.attachments.reconcile-initial-delay-millis:60000}")
public void cleanup() {
try {
Set<String> active = attachments.findActiveStagingKeys();
var deleteBefore = clock.instant().minus(retention);
for (ObjectStorage.StoredObject object : storage.list(PREFIX)) {
if (!active.contains(object.objectKey()) && object.lastModified().isBefore(deleteBefore)) {
storage.delete(object.objectKey());
}
}
} catch (RuntimeException error) {
log.warn("Staging cleanup postponed: {}", error.getMessage());
}
}
}
@@ -0,0 +1,34 @@
package com.example.mtusi_messenger.service;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.crypto.password.PasswordEncoder;
import com.example.mtusi_messenger.dto.CreateUserRequest;
import com.example.mtusi_messenger.exception.ApiExceptions;
import com.example.mtusi_messenger.model.User;
import com.example.mtusi_messenger.repository.UserRepository;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.UUID;
@Service
@RequiredArgsConstructor
public class UserService {
private final UserRepository users;
private final PasswordEncoder passwordEncoder;
public User create(CreateUserRequest r) {
String username = r.username(); String display = r.display_name();
if (users.findByUsername(username).isPresent()) throw ApiExceptions.conflict("Username is already taken");
String passwordHash = passwordEncoder.encode(r.password());
try {
return users.save(new User(UUID.randomUUID(), username, display,
Instant.now().truncatedTo(ChronoUnit.MICROS)), passwordHash);
} catch (DuplicateKeyException e) {
throw ApiExceptions.conflict("Username is already taken");
}
}
public User get(UUID id) { return users.findById(id).orElseThrow(() -> ApiExceptions.unauthorized("Unknown user identity")); }
public boolean exists(UUID id) { return users.findById(id).isPresent(); }
}
@@ -0,0 +1,27 @@
package com.example.mtusi_messenger.service;
import com.example.mtusi_messenger.exception.ApiExceptions;
import java.util.UUID;
import java.util.regex.Pattern;
public final class UuidValidator {
private static final Pattern UUID_PATTERN = Pattern.compile(
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"
);
private UuidValidator() {}
public static UUID parse(String value) {
if (value == null || !UUID_PATTERN.matcher(value).matches()) {
throw ApiExceptions.invalid("Invalid UUID");
}
try {
return UUID.fromString(value);
} catch (IllegalArgumentException e) {
throw ApiExceptions.invalid("Invalid UUID");
}
}
}
@@ -0,0 +1,92 @@
package com.example.mtusi_messenger.storage;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.ListObjectsArgs;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import okhttp3.OkHttpClient;
import java.io.ByteArrayInputStream;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
@Component
public class MinioObjectStorage implements ObjectStorage {
private final MinioClient client;
private final String bucket;
public MinioObjectStorage(
@Value("${messenger.s3.endpoint}") String endpoint,
@Value("${messenger.s3.access-key}") String accessKey,
@Value("${messenger.s3.secret-key}") String secretKey,
@Value("${messenger.s3.bucket}") String bucket,
@Value("${messenger.s3.region:us-east-1}") String region
) {
OkHttpClient httpClient = new OkHttpClient.Builder()
.connectTimeout(Duration.ofSeconds(2))
.readTimeout(Duration.ofSeconds(10))
.writeTimeout(Duration.ofSeconds(10))
.callTimeout(Duration.ofSeconds(15))
.build();
this.client = MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKey, secretKey)
.region(region)
.httpClient(httpClient)
.build();
this.bucket = bucket;
}
@Override
public void put(String objectKey, byte[] bytes, String contentType) {
try (var stream = new ByteArrayInputStream(bytes)) {
client.putObject(PutObjectArgs.builder()
.bucket(bucket)
.object(objectKey)
.contentType(contentType)
.stream(stream, bytes.length, -1)
.build());
} catch (Exception error) {
throw new ObjectStorageException("Cannot write attachment object", error);
}
}
@Override
public byte[] get(String objectKey) {
try (var stream = client.getObject(GetObjectArgs.builder()
.bucket(bucket).object(objectKey).build())) {
return stream.readAllBytes();
} catch (Exception error) {
throw new ObjectStorageException("Cannot read attachment object", error);
}
}
@Override
public void delete(String objectKey) {
try {
client.removeObject(RemoveObjectArgs.builder()
.bucket(bucket).object(objectKey).build());
} catch (Exception error) {
throw new ObjectStorageException("Cannot remove attachment object", error);
}
}
@Override
public List<StoredObject> list(String prefix) {
try {
List<StoredObject> objects = new ArrayList<>();
for (var result : client.listObjects(ListObjectsArgs.builder()
.bucket(bucket).prefix(prefix).recursive(true).build())) {
var item = result.get();
objects.add(new StoredObject(item.objectName(), item.lastModified().toInstant(), item.size()));
}
return List.copyOf(objects);
} catch (Exception error) {
throw new ObjectStorageException("Cannot list attachment objects", error);
}
}
}
@@ -0,0 +1,14 @@
package com.example.mtusi_messenger.storage;
import java.time.Instant;
import java.util.List;
public interface ObjectStorage {
void put(String objectKey, byte[] bytes, String contentType);
byte[] get(String objectKey);
void delete(String objectKey);
List<StoredObject> list(String prefix);
record StoredObject(String objectKey, Instant lastModified, long sizeBytes) {
}
}
@@ -0,0 +1,7 @@
package com.example.mtusi_messenger.storage;
public class ObjectStorageException extends RuntimeException {
public ObjectStorageException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,56 @@
package com.example.mtusi_messenger.web;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.dao.DataAccessException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import com.example.mtusi_messenger.dto.ErrorResponse;
import com.example.mtusi_messenger.exception.ApiException;
import com.example.mtusi_messenger.storage.ObjectStorageException;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ApiException.class)
ResponseEntity<ErrorResponse> api(ApiException e, HttpServletRequest req) {
var body = body(e.code(), e.getMessage(), req);
var builder = ResponseEntity.status(e.status());
if (e.status() == HttpStatus.UNAUTHORIZED && e.authenticate() != null) {
builder.header("WWW-Authenticate", e.authenticate());
}
if (e.status() == HttpStatus.TOO_MANY_REQUESTS) {
builder.header("Retry-After", "1");
}
return builder.body(body);
}
@ExceptionHandler({MethodArgumentNotValidException.class, MethodArgumentTypeMismatchException.class, HttpMessageNotReadableException.class})
ResponseEntity<ErrorResponse> bad(Exception e, HttpServletRequest req) { return ResponseEntity.badRequest().body(body("invalid_request", "Invalid request", req)); }
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
ResponseEntity<ErrorResponse> unsupported(HttpServletRequest req) { return ResponseEntity.status(415).body(body("unsupported_media_type", "Unsupported media type", req)); }
@ExceptionHandler(DataAccessException.class)
ResponseEntity<ErrorResponse> unavailable(DataAccessException e, HttpServletRequest req) {
return ResponseEntity.status(503).body(body("unavailable", "Storage temporarily unavailable", req));
}
@ExceptionHandler(ObjectStorageException.class)
ResponseEntity<ErrorResponse> storageUnavailable(ObjectStorageException e, HttpServletRequest req) {
return ResponseEntity.status(503).body(body("unavailable", "Object storage temporarily unavailable", req));
}
@ExceptionHandler(Exception.class)
ResponseEntity<ErrorResponse> internal(Exception e, HttpServletRequest req) { return ResponseEntity.status(500).body(body("internal_error", "Internal server error", req)); }
private ErrorResponse body(
String code,
String message,
HttpServletRequest req
) {
String id = (String) req.getAttribute(RequestIdFilter.ATTRIBUTE);
return new ErrorResponse(
new ErrorResponse.ErrorBody(code, message, id)
);
}
}
@@ -0,0 +1,47 @@
package com.example.mtusi_messenger.web;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class InstanceIdFilter extends OncePerRequestFilter {
public static final String HEADER = "X-Instance-Id";
private final String instanceId;
public InstanceIdFilter() {
String configured = System.getenv("INSTANCE_ID");
this.instanceId = configured == null || configured.isBlank()
? localHostOrRandom()
: configured;
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain
) throws ServletException, IOException {
response.setHeader(HEADER, instanceId);
filterChain.doFilter(request, response);
}
private static String localHostOrRandom() {
try {
return InetAddress.getLocalHost().getHostName();
} catch (UnknownHostException e) {
return "api-" + UUID.randomUUID();
}
}
}
@@ -0,0 +1,21 @@
package com.example.mtusi_messenger.web;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Documented
@Constraint(validatedBy = UnicodeBlankValidator.class)
@Target({ FIELD, PARAMETER, RECORD_COMPONENT, ANNOTATION_TYPE })
@Retention(RUNTIME)
public @interface NotUnicodeBlank {
String message() default "must not be blank";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
@@ -0,0 +1,56 @@
package com.example.mtusi_messenger.web;
import com.example.mtusi_messenger.dto.ErrorResponse;
import com.example.mtusi_messenger.service.ReadinessService;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
@Component
public class ReadinessGuardFilter extends OncePerRequestFilter {
private final ReadinessService readiness;
private final ObjectMapper mapper;
public ReadinessGuardFilter(ReadinessService readiness, ObjectMapper mapper) {
this.readiness = readiness;
this.mapper = mapper;
}
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
String path = request.getRequestURI();
return path.startsWith("/health/")
|| path.equals("/swagger-ui.html")
|| path.startsWith("/swagger-ui/")
|| path.startsWith("/v3/api-docs/")
|| path.equals("/v3/api-docs");
}
@Override
protected void doFilterInternal(
HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain
) throws ServletException, IOException {
if (readiness.acceptsBusinessTraffic()) {
filterChain.doFilter(request, response);
return;
}
response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
String requestId = (String) request.getAttribute(RequestIdFilter.ATTRIBUTE);
mapper.writeValue(response.getOutputStream(), new ErrorResponse(
new ErrorResponse.ErrorBody(
"unavailable",
"Application is not ready to serve business traffic",
requestId)));
}
}
@@ -0,0 +1,56 @@
package com.example.mtusi_messenger.web;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.UUID;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestIdFilter extends OncePerRequestFilter {
private static final Logger log = LoggerFactory.getLogger(RequestIdFilter.class);
public static final String HEADER = "X-Request-Id";
public static final String ATTRIBUTE = "request_id";
@Override
protected void doFilterInternal(
HttpServletRequest req,
HttpServletResponse res,
FilterChain chain
) throws ServletException, IOException {
String id = UUID.randomUUID().toString();
req.setAttribute(ATTRIBUTE, id);
res.setHeader(HEADER, id);
try {
MDC.put(ATTRIBUTE, id);
chain.doFilter(req, res);
} finally {
Object routeAttribute = req.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
String route = routeAttribute == null ? null : routeAttribute.toString();
if (route != null && !route.startsWith("/health/")) {
log.atInfo()
.addKeyValue("event", "http_request_completed")
.addKeyValue("http.request.method", req.getMethod())
.addKeyValue("http.route", route)
.addKeyValue("http.response.status_code", res.getStatus())
.log("HTTP request completed");
}
MDC.remove(ATTRIBUTE);
}
}
}
@@ -0,0 +1,23 @@
package com.example.mtusi_messenger.web;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class UnicodeBlankValidator
implements ConstraintValidator<NotUnicodeBlank, String> {
@Override
public boolean isValid(
String value,
ConstraintValidatorContext context) {
if (value == null || value.isEmpty()) {
return false;
}
return value.codePoints().anyMatch(codePoint ->
!Character.isWhitespace(codePoint)
&& !Character.isSpaceChar(codePoint)
);
}
}
@@ -0,0 +1,35 @@
package com.example.mtusi_messenger.web;
import jakarta.validation.Constraint;
import jakarta.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Documented
@Constraint(validatedBy = UnicodeSizeValidator.class)
@Target({
FIELD,
METHOD,
PARAMETER,
ANNOTATION_TYPE
})
@Retention(RUNTIME)
public @interface UnicodeSize {
String message() default "size must be between {min} and {max} Unicode code points";
int min() default 0;
int max() default Integer.MAX_VALUE;
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
@@ -0,0 +1,32 @@
package com.example.mtusi_messenger.web;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
public class UnicodeSizeValidator
implements ConstraintValidator<UnicodeSize, String> {
private int min;
private int max;
@Override
public void initialize(UnicodeSize annotation) {
this.min = annotation.min();
this.max = annotation.max();
}
@Override
public boolean isValid(
String value,
ConstraintValidatorContext context
) {
if (value == null) {
return true;
}
int codePointCount = value.codePointCount(0, value.length());
return codePointCount >= min
&& codePointCount <= max;
}
}
@@ -0,0 +1,315 @@
package com.example.mtusi_messenger.worker;
import com.example.mtusi_messenger.model.Attachment;
import com.example.mtusi_messenger.model.AttachmentJob;
import com.example.mtusi_messenger.model.AttachmentVariant;
import com.example.mtusi_messenger.observability.JobTelemetry;
import com.example.mtusi_messenger.queue.RetryPolicy;
import com.example.mtusi_messenger.repository.AttachmentRepository;
import com.example.mtusi_messenger.storage.ObjectStorage;
import com.example.mtusi_messenger.storage.ObjectStorageException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import jakarta.annotation.PreDestroy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Clock;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
@Component
@ConditionalOnProperty(name = "messenger.role", havingValue = "worker")
public class AttachmentWorker {
private static final Logger log = LoggerFactory.getLogger(AttachmentWorker.class);
private final ObjectMapper mapper;
private final AttachmentRepository attachments;
private final ObjectStorage storage;
private final ImageVariantProcessor images;
private final RetryPolicy retryPolicy;
private final TransactionTemplate transaction;
private final JobTelemetry telemetry;
private final int maxAttempts;
private final Duration jobTimeout;
private final Duration leaseDuration;
private final boolean injectCrashBeforeSideEffect;
private final boolean injectCrashAfterSideEffect;
private final boolean injectCrashAfterResultCommit;
private final ExecutorService processingPool;
private final Clock clock = Clock.systemUTC();
public AttachmentWorker(
ObjectMapper mapper,
AttachmentRepository attachments,
ObjectStorage storage,
ImageVariantProcessor images,
RetryPolicy retryPolicy,
TransactionTemplate transaction,
JobTelemetry telemetry,
@Value("${messenger.jobs.max-attempts:5}") int maxAttempts,
@Value("${messenger.jobs.timeout:60s}") Duration jobTimeout,
@Value("${messenger.jobs.lease-duration:90s}") Duration leaseDuration,
@Value("${messenger.jobs.fault-crash-before-side-effect:false}") boolean injectCrashBeforeSideEffect,
@Value("${messenger.jobs.fault-crash-after-side-effect:false}") boolean injectCrashAfterSideEffect,
@Value("${messenger.jobs.fault-crash-after-result-commit:false}") boolean injectCrashAfterResultCommit,
@Value("${spring.rabbitmq.listener.simple.concurrency:2}") int concurrency) {
if (maxAttempts < 1 || jobTimeout.isZero() || jobTimeout.isNegative()
|| leaseDuration.compareTo(jobTimeout) <= 0 || concurrency < 1) {
throw new IllegalArgumentException("Invalid attachment worker limits");
}
this.mapper = mapper;
this.attachments = attachments;
this.storage = storage;
this.images = images;
this.retryPolicy = retryPolicy;
this.transaction = transaction;
this.telemetry = telemetry;
this.maxAttempts = maxAttempts;
this.jobTimeout = jobTimeout;
this.leaseDuration = leaseDuration;
this.injectCrashBeforeSideEffect = injectCrashBeforeSideEffect;
this.injectCrashAfterSideEffect = injectCrashAfterSideEffect;
this.injectCrashAfterResultCommit = injectCrashAfterResultCommit;
this.processingPool = Executors.newFixedThreadPool(concurrency,
Thread.ofPlatform().name("attachment-image-", 0).factory());
}
@RabbitListener(queues = "${messenger.jobs.queue}")
public void consume(Message message, Channel channel) throws IOException {
long deliveryTag = message.getMessageProperties().getDeliveryTag();
AttachmentJob job;
try {
job = mapper.readValue(message.getBody(), AttachmentJob.class);
} catch (RuntimeException | IOException invalidMessage) {
telemetry.malformedMessage();
log.atError()
.addKeyValue("event", "attachment_job_rejected")
.addKeyValue("outcome", "invalid_message")
.log("Rejecting malformed attachment job message");
channel.basicReject(deliveryTag, false);
return;
}
Attachment attachment = attachments.findById(job.attachmentId()).orElse(null);
if (attachment == null || "ready".equals(attachment.status()) || "failed".equals(attachment.status())) {
channel.basicAck(deliveryTag, false);
return;
}
int attempt = Math.max(job.attempt(), attachments.currentAttempt(job.jobId()));
UUID leaseToken = UUID.randomUUID();
boolean claimed = Boolean.TRUE.equals(transaction.execute(status ->
attachments.claim(job.jobId(), job.attachmentId(), job.pipelineVersion(),
attempt, leaseToken, leaseDuration)));
if (!claimed) {
// A live worker owns the lease, or a terminal state won the race.
// If the owner died, the DB lease reaper will create a new outbox delivery.
channel.basicAck(deliveryTag, false);
return;
}
long startedNanos = telemetry.started();
String outcome = "error";
Future<ProcessOutcome> future = processingPool.submit(() -> process(job, leaseToken));
try {
ProcessOutcome processOutcome = future.get(jobTimeout.toMillis(), TimeUnit.MILLISECONDS);
if (processOutcome.crashAfterCommit()) {
log.atError().addKeyValue("event", "fault_after_result_commit")
.log("Fault injection: halting worker after durable result and before consumer ack");
Runtime.getRuntime().halt(86);
}
channel.basicAck(deliveryTag, false);
outcome = "success";
log.atInfo()
.addKeyValue("event", "attachment_job_completed")
.addKeyValue("job.type", AttachmentJob.TYPE)
.addKeyValue("outcome", outcome)
.log("Attachment job completed");
} catch (TimeoutException timeout) {
future.cancel(true);
retryOrFail(job, leaseToken, attempt, "processing_timeout", deliveryTag, channel);
outcome = attempt >= maxAttempts ? "failed" : "retry";
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
future.cancel(true);
channel.basicNack(deliveryTag, false, true);
outcome = "interrupted";
} catch (ExecutionException execution) {
Throwable cause = execution.getCause();
if (cause instanceof ImageVariantProcessor.ProcessingException imageFailure
&& imageFailure.permanent()) {
failPermanent(job, leaseToken, imageFailure.errorCode(), deliveryTag, channel);
outcome = "failed";
} else {
String code = cause instanceof ImageVariantProcessor.ProcessingException imageFailure
? imageFailure.errorCode() : "processing_failed";
retryOrFail(job, leaseToken, attempt, code, deliveryTag, channel);
outcome = attempt >= maxAttempts ? "failed" : "retry";
}
} finally {
telemetry.finished(startedNanos, job.createdAt(), outcome);
}
}
private ProcessOutcome process(AttachmentJob job, UUID leaseToken) {
if (injectCrashBeforeSideEffect
&& attachments.markBeforeEffectFaultInjected(job.jobId(), leaseToken)) {
log.atError().addKeyValue("event", "fault_before_side_effect")
.log("Fault injection: halting worker before object-storage side effect");
Runtime.getRuntime().halt(84);
}
Attachment attachment = attachments.findById(job.attachmentId())
.orElseThrow(() -> new ImageVariantProcessor.ProcessingException(
"attachment_missing", true, "Attachment metadata is missing", null));
byte[] original = loadOriginal(attachment);
if (original.length != attachment.sizeBytes() || !sha256(original).equals(attachment.sha256())) {
throw new ImageVariantProcessor.ProcessingException(
"invalid_image", true, "Staging checksum mismatch", null);
}
storage.put(attachment.objectKey(), original, attachment.contentType());
List<ImageVariantProcessor.GeneratedVariant> generated =
images.createVariants(original, job.pipelineVersion());
List<AttachmentVariant> variants = new ArrayList<>(generated.size());
for (ImageVariantProcessor.GeneratedVariant item : generated) {
String objectKey = "attachments/" + attachment.id() + "/"
+ item.name() + "-v" + job.pipelineVersion() + "." + item.extension();
storage.put(objectKey, item.bytes(), item.contentType());
variants.add(new AttachmentVariant(
item.name(), item.contentType(), item.bytes().length,
item.width(), item.height(), sha256(item.bytes()), objectKey));
}
if (injectCrashAfterSideEffect
&& attachments.markAfterEffectFaultInjected(job.jobId(), leaseToken)) {
log.atError().addKeyValue("event", "fault_after_side_effect")
.log("Fault injection: halting worker after object-storage side effect before result commit");
Runtime.getRuntime().halt(85);
}
AttachmentRepository.CompletionResult completion = transaction.execute(status ->
attachments.markReady(job.jobId(), job.attachmentId(), leaseToken,
job.pipelineVersion(), variants, injectCrashAfterResultCommit));
if (completion == null || !completion.completed()) {
return new ProcessOutcome(false);
}
try {
storage.delete(attachment.stagingKey());
} catch (RuntimeException cleanupFailure) {
log.atWarn().addKeyValue("event", "staging_cleanup_postponed")
.log("Staging cleanup postponed after attachment processing");
}
return new ProcessOutcome(completion.crashAfterCommit());
}
private byte[] loadOriginal(Attachment attachment) {
try {
return storage.get(attachment.stagingKey());
} catch (ObjectStorageException missingStaging) {
try {
// A pipeline promotion reuses the immutable final original after
// the previous version safely removed its staging object.
return storage.get(attachment.objectKey());
} catch (ObjectStorageException missingOriginal) {
missingOriginal.addSuppressed(missingStaging);
throw missingOriginal;
}
}
}
private void failPermanent(
AttachmentJob job, UUID leaseToken, String errorCode,
long deliveryTag, Channel channel) throws IOException {
boolean failed = Boolean.TRUE.equals(transaction.execute(status ->
attachments.markFailed(job.jobId(), job.attachmentId(), job.pipelineVersion(),
leaseToken, errorCode)));
if (failed) {
channel.basicReject(deliveryTag, false);
} else {
channel.basicAck(deliveryTag, false);
}
}
private void retryOrFail(
AttachmentJob job, UUID leaseToken, int attempt, String errorCode,
long deliveryTag, Channel channel) throws IOException {
try {
if (attempt >= maxAttempts) {
boolean failed = Boolean.TRUE.equals(transaction.execute(status ->
attachments.markFailed(job.jobId(), job.attachmentId(),
job.pipelineVersion(), leaseToken, "retry_exhausted")));
if (failed) {
log.atError()
.addKeyValue("event", "attachment_job_retry_exhausted")
.addKeyValue("job.type", AttachmentJob.TYPE)
.addKeyValue("outcome", "failed")
.addKeyValue("attempt", attempt)
.addKeyValue("error.code", errorCode)
.log("Attachment job exhausted retry attempts");
channel.basicReject(deliveryTag, false);
} else {
channel.basicAck(deliveryTag, false);
}
return;
}
int nextAttempt = attempt + 1;
boolean queued = Boolean.TRUE.equals(transaction.execute(status ->
attachments.markQueuedForRetry(
job.jobId(), job.attachmentId(), job.pipelineVersion(),
leaseToken, nextAttempt, errorCode,
clock.instant().plus(retryPolicy.delayForAttempt(nextAttempt)))));
// The DB outbox is now the durable retry carrier; the current broker
// delivery can be acknowledged without a DB/broker dual write.
channel.basicAck(deliveryTag, false);
if (queued) {
log.atWarn()
.addKeyValue("event", "attachment_job_retry_scheduled")
.addKeyValue("job.type", AttachmentJob.TYPE)
.addKeyValue("outcome", "retry")
.addKeyValue("attempt", nextAttempt)
.addKeyValue("error.code", errorCode)
.log("Attachment job scheduled for retry");
} else {
log.atInfo().addKeyValue("event", "attachment_job_retry_skipped")
.log("Retry skipped because job lost its lease or became terminal");
}
} catch (RuntimeException databaseFailure) {
channel.basicNack(deliveryTag, false, true);
}
}
@PreDestroy
void shutdownPool() {
processingPool.shutdownNow();
}
private static String sha256(byte[] bytes) {
try {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));
} catch (NoSuchAlgorithmException impossible) {
throw new IllegalStateException("SHA-256 is unavailable", impossible);
}
}
private record ProcessOutcome(boolean crashAfterCommit) {
}
}
@@ -0,0 +1,270 @@
package com.example.mtusi_messenger.worker;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
@Component
public class ImageVariantProcessor {
private static final long MEBIBYTE = 1024L * 1024L;
private static final long OUTPUT_ALLOWANCE_BYTES = 64L * MEBIBYTE;
private final long maxPixels;
private final long memoryBudgetBytes;
private final Semaphore memoryPermits;
private final Duration memoryWait;
public ImageVariantProcessor(
@Value("${messenger.jobs.worker-max-pixels:40000000}") long maxPixels,
@Value("${messenger.jobs.worker-memory-budget-bytes:536870912}") long memoryBudgetBytes,
@Value("${messenger.jobs.memory-wait:2s}") Duration memoryWait) {
if (maxPixels < 1 || memoryBudgetBytes < MEBIBYTE || memoryWait.isNegative()) {
throw new IllegalArgumentException("Invalid worker image resource limits");
}
this.maxPixels = maxPixels;
this.memoryBudgetBytes = memoryBudgetBytes;
this.memoryPermits = new Semaphore((int) Math.min(Integer.MAX_VALUE,
Math.max(1, memoryBudgetBytes / MEBIBYTE)), true);
this.memoryWait = memoryWait;
}
public List<GeneratedVariant> createVariants(byte[] original, int pipelineVersion) {
PipelineProfile profile = PipelineProfile.forVersion(pipelineVersion);
ImageInfo info = inspect(original);
long estimatedBytes;
try {
estimatedBytes = Math.addExact(Math.multiplyExact(info.pixels(), 12L),
OUTPUT_ALLOWANCE_BYTES);
} catch (ArithmeticException overflow) {
throw permanent("image_too_large", "Image memory estimate overflow", overflow);
}
if (estimatedBytes > memoryBudgetBytes) {
throw permanent("image_too_large", "Image exceeds worker memory budget", null);
}
int permits = (int) Math.max(1, (estimatedBytes + MEBIBYTE - 1) / MEBIBYTE);
boolean acquired;
try {
acquired = memoryPermits.tryAcquire(permits, memoryWait.toMillis(), TimeUnit.MILLISECONDS);
} catch (InterruptedException interrupted) {
Thread.currentThread().interrupt();
throw temporary("worker_interrupted", "Interrupted while waiting for memory budget", interrupted);
}
if (!acquired) {
throw temporary("worker_capacity", "Worker memory budget is currently exhausted", null);
}
try {
return transform(original, profile);
} finally {
memoryPermits.release(permits);
}
}
private ImageInfo inspect(byte[] bytes) {
ImageIO.setUseCache(false);
try (var input = ImageIO.createImageInputStream(new ByteArrayInputStream(bytes))) {
if (input == null) {
throw permanent("invalid_image", "Image input is invalid", null);
}
Iterator<ImageReader> readers = ImageIO.getImageReaders(input);
if (!readers.hasNext()) {
throw permanent("invalid_image", "Unsupported image encoding", null);
}
ImageReader reader = readers.next();
try {
reader.setInput(input, true, true);
int width = reader.getWidth(0);
int height = reader.getHeight(0);
long pixels = Math.multiplyExact((long) width, height);
if (width < 1 || height < 1 || pixels > maxPixels) {
throw permanent("image_too_large", "Image exceeds worker pixel limit", null);
}
return new ImageInfo(width, height, pixels);
} finally {
reader.dispose();
}
} catch (ProcessingException error) {
throw error;
} catch (IOException | RuntimeException error) {
throw permanent("invalid_image", "Image header cannot be read", error);
}
}
private List<GeneratedVariant> transform(byte[] original, PipelineProfile profile) {
try {
BufferedImage oriented = Thumbnails.of(new ByteArrayInputStream(original))
.useExifOrientation(true)
.scale(1.0)
.asBufferedImage();
if (oriented == null || oriented.getWidth() < 1 || oriented.getHeight() < 1) {
throw permanent("invalid_image", "Image cannot be decoded", null);
}
try {
List<GeneratedVariant> variants = new ArrayList<>(3);
BufferedImage thumbnail = fit(oriented, 256, BufferedImage.TYPE_INT_RGB, true);
variants.add(encode("thumbnail", "image/jpeg", "jpg", thumbnail, "jpeg",
profile.thumbnailQuality()));
thumbnail.flush();
BufferedImage crop = cropSquare(oriented, 128);
variants.add(encode("crop", "image/jpeg", "jpg", crop, "jpeg",
profile.cropQuality()));
crop.flush();
int webpType = oriented.getColorModel().hasAlpha()
? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB;
BufferedImage optimized = fit(oriented, 1280, webpType, !oriented.getColorModel().hasAlpha());
variants.add(encode("optimized", "image/webp", "webp", optimized, "webp",
profile.webpQuality()));
optimized.flush();
return List.copyOf(variants);
} finally {
oriented.flush();
}
} catch (ProcessingException error) {
throw error;
} catch (IOException | RuntimeException error) {
throw permanent("invalid_image", "Image cannot be transformed", error);
}
}
private static BufferedImage fit(BufferedImage source, int maxSide, int type, boolean whiteBackground) {
double scale = Math.min(1.0, Math.min(
(double) maxSide / source.getWidth(),
(double) maxSide / source.getHeight()));
int width = Math.max(1, (int) Math.floor(source.getWidth() * scale));
int height = Math.max(1, (int) Math.floor(source.getHeight() * scale));
BufferedImage target = new BufferedImage(width, height, type);
Graphics2D graphics = qualityGraphics(target, whiteBackground);
try {
graphics.drawImage(source, 0, 0, width, height, null);
} finally {
graphics.dispose();
}
return target;
}
private static BufferedImage cropSquare(BufferedImage source, int side) {
int sourceSide = Math.min(source.getWidth(), source.getHeight());
int x = (source.getWidth() - sourceSide) / 2;
int y = (source.getHeight() - sourceSide) / 2;
BufferedImage target = new BufferedImage(side, side, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = qualityGraphics(target, true);
try {
graphics.drawImage(source, 0, 0, side, side,
x, y, x + sourceSide, y + sourceSide, null);
} finally {
graphics.dispose();
}
return target;
}
private static Graphics2D qualityGraphics(BufferedImage target, boolean whiteBackground) {
Graphics2D graphics = target.createGraphics();
if (whiteBackground) {
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, target.getWidth(), target.getHeight());
}
graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_BICUBIC);
graphics.setRenderingHint(RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY);
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
return graphics;
}
private static GeneratedVariant encode(
String name, String contentType, String extension,
BufferedImage image, String format, float quality) throws IOException {
Iterator<javax.imageio.ImageWriter> writers = ImageIO.getImageWritersByFormatName(format);
if (!writers.hasNext()) {
throw new IOException(format + " writer is unavailable");
}
var writer = writers.next();
try (var output = new ByteArrayOutputStream();
var imageOutput = ImageIO.createImageOutputStream(output)) {
writer.setOutput(imageOutput);
ImageWriteParam parameters = writer.getDefaultWriteParam();
if (parameters.canWriteCompressed()) {
parameters.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
String[] compressionTypes = parameters.getCompressionTypes();
if (compressionTypes != null && compressionTypes.length > 0) {
parameters.setCompressionType(compressionTypes[0]);
}
parameters.setCompressionQuality(quality);
}
// Source metadata is intentionally omitted for every generated variant.
writer.write(null, new IIOImage(image, null, null), parameters);
imageOutput.flush();
return new GeneratedVariant(name, contentType, extension, output.toByteArray(),
image.getWidth(), image.getHeight());
} finally {
writer.dispose();
}
}
private static ProcessingException permanent(String code, String message, Throwable cause) {
return new ProcessingException(code, true, message, cause);
}
private static ProcessingException temporary(String code, String message, Throwable cause) {
return new ProcessingException(code, false, message, cause);
}
private record ImageInfo(int width, int height, long pixels) {
}
private record PipelineProfile(
int version, float thumbnailQuality, float cropQuality, float webpQuality) {
private static PipelineProfile forVersion(int version) {
return switch (version) {
case 1 -> new PipelineProfile(1, 0.85f, 0.88f, 0.82f);
case 2 -> new PipelineProfile(2, 0.87f, 0.90f, 0.84f);
default -> throw permanent(
"unsupported_pipeline", "Unsupported pipeline version " + version, null);
};
}
}
public record GeneratedVariant(String name, String contentType, String extension,
byte[] bytes, int width, int height) {
}
public static final class ProcessingException extends RuntimeException {
private final String errorCode;
private final boolean permanent;
public ProcessingException(
String errorCode, boolean permanent, String message, Throwable cause) {
super(message, cause);
this.errorCode = errorCode;
this.permanent = permanent;
}
public String errorCode() {
return errorCode;
}
public boolean permanent() {
return permanent;
}
}
}