ЛР6: наблюдаемость, SLO и диагностика отказов
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
package ru.mtusi.messenger;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
import org.springframework.boot.security.autoconfigure.UserDetailsServiceAutoConfiguration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@ConfigurationPropertiesScan
|
||||
@SpringBootApplication(exclude = UserDetailsServiceAutoConfiguration.class)
|
||||
@EnableScheduling
|
||||
public class MessengerLab1Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(MessengerLab1Application.class, args);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package ru.mtusi.messenger.cache;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
@Component
|
||||
public class CacheHealthTracker {
|
||||
|
||||
private final AtomicBoolean stale = new AtomicBoolean(false);
|
||||
|
||||
public void markStale() {
|
||||
stale.set(true);
|
||||
}
|
||||
|
||||
public boolean consumeStale() {
|
||||
return stale.getAndSet(false);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import org.springframework.boot.jackson.autoconfigure.JsonMapperBuilderCustomizer;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import tools.jackson.databind.DeserializationFeature;
|
||||
import tools.jackson.databind.cfg.CoercionAction;
|
||||
import tools.jackson.databind.cfg.CoercionInputShape;
|
||||
|
||||
@Configuration
|
||||
@Slf4j
|
||||
public class JacksonConfig {
|
||||
|
||||
@Bean
|
||||
public JsonMapperBuilderCustomizer strictJacksonCustomizer() {
|
||||
log.warn(">>> Strict JsonMapper customizer applied");
|
||||
return builder ->
|
||||
builder.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
|
||||
.withCoercionConfigDefaults(
|
||||
config -> {
|
||||
config.setCoercion(
|
||||
CoercionInputShape.Boolean, CoercionAction.Fail);
|
||||
config.setCoercion(
|
||||
CoercionInputShape.Integer, CoercionAction.Fail);
|
||||
config.setCoercion(
|
||||
CoercionInputShape.Float, CoercionAction.Fail);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import io.minio.MinioClient;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import ru.mtusi.messenger.config.properties.S3Properties;
|
||||
|
||||
@Configuration
|
||||
@RequiredArgsConstructor
|
||||
public class MinioConfig {
|
||||
private final S3Properties props;
|
||||
|
||||
@Bean
|
||||
public MinioClient minioClient() {
|
||||
return MinioClient.builder()
|
||||
.endpoint(props.endpoint())
|
||||
.httpClient(
|
||||
new okhttp3.OkHttpClient.Builder()
|
||||
.connectTimeout(java.time.Duration.ofSeconds(2))
|
||||
.readTimeout(java.time.Duration.ofSeconds(10))
|
||||
.writeTimeout(java.time.Duration.ofSeconds(10))
|
||||
.callTimeout(java.time.Duration.ofSeconds(20))
|
||||
.build())
|
||||
.region(props.region())
|
||||
.credentials(props.resolvedAccessKey(), props.resolvedSecretKey())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package ru.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;
|
||||
|
||||
@Configuration
|
||||
@SecurityScheme(name = "basicAuth", type = SecuritySchemeType.HTTP, scheme = "basic")
|
||||
@SecurityScheme(
|
||||
name = "bearerAuth",
|
||||
type = SecuritySchemeType.HTTP,
|
||||
scheme = "bearer",
|
||||
bearerFormat = "opaque session token")
|
||||
public class OpenApiConfig {}
|
||||
@@ -0,0 +1,29 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import io.github.bucket4j.Bandwidth;
|
||||
import io.github.bucket4j.Bucket;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import ru.mtusi.messenger.config.properties.RateLimitProperties;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@Configuration
|
||||
@RequiredArgsConstructor
|
||||
public class RateLimitConfig {
|
||||
private final RateLimitProperties props;
|
||||
|
||||
@Bean
|
||||
public Bucket rateLimitBucket() {
|
||||
Bandwidth limit =
|
||||
Bandwidth.builder()
|
||||
.capacity(props.ratePerMinute())
|
||||
.refillGreedy(props.ratePerMinute(), Duration.ofMinutes(1))
|
||||
.build();
|
||||
return Bucket.builder().addLimit(limit).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import io.lettuce.core.ClientOptions;
|
||||
import io.lettuce.core.SocketOptions;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.annotation.CachingConfigurer;
|
||||
import org.springframework.cache.annotation.EnableCaching;
|
||||
import org.springframework.cache.interceptor.CacheErrorHandler;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.cache.RedisCacheConfiguration;
|
||||
import org.springframework.data.redis.cache.RedisCacheManager;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
|
||||
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
|
||||
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
|
||||
import org.springframework.data.redis.serializer.JacksonJsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.RedisSerializationContext;
|
||||
|
||||
import ru.mtusi.messenger.cache.CacheHealthTracker;
|
||||
import ru.mtusi.messenger.config.properties.RedisProperties;
|
||||
import ru.mtusi.messenger.config.properties.SessionProperties;
|
||||
import ru.mtusi.messenger.service.SessionService;
|
||||
|
||||
@Slf4j
|
||||
@Configuration
|
||||
@EnableCaching
|
||||
@EnableConfigurationProperties(RedisProperties.class)
|
||||
@RequiredArgsConstructor
|
||||
public class RedisConfig implements CachingConfigurer {
|
||||
private final SessionProperties sessionProperties;
|
||||
private final RedisProperties redisProperties;
|
||||
private final CacheHealthTracker cacheHealthTracker;
|
||||
|
||||
@Bean
|
||||
public RedisConnectionFactory redisConnectionFactory() {
|
||||
RedisStandaloneConfiguration server =
|
||||
new RedisStandaloneConfiguration(redisProperties.host(), redisProperties.port());
|
||||
|
||||
SocketOptions socketOptions =
|
||||
SocketOptions.builder()
|
||||
.connectTimeout(redisProperties.connectTimeout())
|
||||
.keepAlive(
|
||||
SocketOptions.KeepAliveOptions.builder()
|
||||
.enable()
|
||||
.idle(redisProperties.keepAliveIdle())
|
||||
.interval(redisProperties.keepAliveInterval())
|
||||
.count(3)
|
||||
.build())
|
||||
.tcpUserTimeout(
|
||||
SocketOptions.TcpUserTimeoutOptions.builder()
|
||||
.tcpUserTimeout(redisProperties.tcpUserTimeout())
|
||||
.enable()
|
||||
.build())
|
||||
.build();
|
||||
|
||||
ClientOptions clientOptions =
|
||||
ClientOptions.builder().socketOptions(socketOptions).autoReconnect(true).build();
|
||||
|
||||
LettuceClientConfiguration client =
|
||||
LettuceClientConfiguration.builder()
|
||||
.commandTimeout(redisProperties.commandTimeout())
|
||||
.shutdownTimeout(redisProperties.shutdownTimeout())
|
||||
.clientOptions(clientOptions)
|
||||
.build();
|
||||
|
||||
return new LettuceConnectionFactory(server, client);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RedisCacheManager cacheManager(RedisConnectionFactory cf) {
|
||||
RedisCacheConfiguration cfg =
|
||||
RedisCacheConfiguration.defaultCacheConfig()
|
||||
.entryTtl(sessionProperties.ttl())
|
||||
.disableCachingNullValues()
|
||||
.serializeValuesWith(
|
||||
RedisSerializationContext.SerializationPair.fromSerializer(
|
||||
new JacksonJsonRedisSerializer<>(
|
||||
SessionService.SessionRecord.class)));
|
||||
return RedisCacheManager.builder(cf).cacheDefaults(cfg).build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public CacheErrorHandler errorHandler() {
|
||||
return new CacheErrorHandler() {
|
||||
@Override
|
||||
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
|
||||
cacheHealthTracker.markStale();
|
||||
log.warn("Cache GET failed ({}): {}", cache.getName(), e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleCachePutError(
|
||||
RuntimeException e, Cache cache, Object key, Object value) {
|
||||
cacheHealthTracker.markStale();
|
||||
log.warn("Cache PUT failed ({}): {}", cache.getName(), e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
|
||||
cacheHealthTracker.markStale();
|
||||
log.warn("Cache EVICT failed ({}): {}", cache.getName(), e.getMessage());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void handleCacheClearError(RuntimeException e, Cache cache) {
|
||||
cacheHealthTracker.markStale();
|
||||
log.warn("Cache CLEAR failed ({}): {}", cache.getName(), e.getMessage());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package ru.mtusi.messenger.config;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
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.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.crypto.argon2.Argon2PasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
|
||||
import org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
import ru.mtusi.messenger.exception.ApiErrorFactory;
|
||||
import ru.mtusi.messenger.security.ApiAuthenticationEntryPoint;
|
||||
import ru.mtusi.messenger.security.SessionAuthenticationFilter;
|
||||
import ru.mtusi.messenger.security.SessionAuthenticationProvider;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@RequiredArgsConstructor
|
||||
public class SecurityConfig {
|
||||
private final SessionAuthenticationProvider sessionAuthenticationProvider;
|
||||
private final ApiAuthenticationEntryPoint entryPoint;
|
||||
private final ApiErrorFactory errors;
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return Argon2PasswordEncoder.defaultsForSpringSecurity_v5_8();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticationManager authenticationManager() {
|
||||
return new ProviderManager(sessionAuthenticationProvider);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(
|
||||
HttpSecurity http,
|
||||
AuthenticationManager authenticationManager,
|
||||
BearerTokenResolver bearerTokenResolver)
|
||||
throws Exception {
|
||||
SessionAuthenticationFilter sessionFilter =
|
||||
new SessionAuthenticationFilter(bearerTokenResolver, authenticationManager, errors);
|
||||
|
||||
http.csrf(AbstractHttpConfigurer::disable)
|
||||
.httpBasic(AbstractHttpConfigurer::disable)
|
||||
.formLogin(AbstractHttpConfigurer::disable)
|
||||
.logout(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(
|
||||
auth ->
|
||||
auth.requestMatchers("/health/**")
|
||||
.permitAll()
|
||||
.requestMatchers(
|
||||
"/swagger-ui.html",
|
||||
"/swagger-ui/**",
|
||||
"/v3/api-docs",
|
||||
"/v3/api-docs/**")
|
||||
.permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/v1/users")
|
||||
.permitAll()
|
||||
.requestMatchers(HttpMethod.POST, "/api/v1/auth/sessions")
|
||||
.permitAll()
|
||||
.requestMatchers("/actuator/health", "/actuator/health/**")
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
.authenticated())
|
||||
.addFilterBefore(sessionFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.exceptionHandling(eh -> eh.authenticationEntryPoint(entryPoint));
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public BearerTokenResolver bearerTokenResolver() {
|
||||
return new DefaultBearerTokenResolver();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package ru.mtusi.messenger.config.properties;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "app.limits")
|
||||
public record AppProperties(int maxMessagesPerChat) {}
|
||||
@@ -0,0 +1,6 @@
|
||||
package ru.mtusi.messenger.config.properties;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "app.idempotency")
|
||||
public record IdempotencyProperties(int keyMaxLength, String keyPattern, int retentionHours) {}
|
||||
@@ -0,0 +1,6 @@
|
||||
package ru.mtusi.messenger.config.properties;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "app.instance")
|
||||
public record InstanceProperties(String id) {}
|
||||
@@ -0,0 +1,6 @@
|
||||
package ru.mtusi.messenger.config.properties;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
@ConfigurationProperties(prefix = "app.rate")
|
||||
public record RateLimitProperties(int ratePerMinute, int retryAfterSeconds) {}
|
||||
@@ -0,0 +1,16 @@
|
||||
package ru.mtusi.messenger.config.properties;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@ConfigurationProperties(prefix = "app.redis")
|
||||
public record RedisProperties(
|
||||
String host,
|
||||
int port,
|
||||
Duration commandTimeout,
|
||||
Duration connectTimeout,
|
||||
Duration shutdownTimeout,
|
||||
Duration keepAliveIdle,
|
||||
Duration keepAliveInterval,
|
||||
Duration tcpUserTimeout) {}
|
||||
@@ -0,0 +1,40 @@
|
||||
package ru.mtusi.messenger.config.properties;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.bind.DefaultValue;
|
||||
|
||||
@ConfigurationProperties(prefix = "s3")
|
||||
public record S3Properties(
|
||||
String endpoint,
|
||||
String bucket,
|
||||
@DefaultValue("us-east-1") String region,
|
||||
@DefaultValue("") String accessKey,
|
||||
@DefaultValue("") String secretKey,
|
||||
@DefaultValue("true") boolean pathStyleAccess,
|
||||
@DefaultValue("300") int presignExpirySeconds) {
|
||||
public String resolvedAccessKey() {
|
||||
var file = System.getenv("S3_ACCESS_KEY_ID_FILE");
|
||||
if (file != null && !file.isBlank()) {
|
||||
try {
|
||||
return new String(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(file)))
|
||||
.strip();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to read S3_ACCESS_KEY_ID_FILE: " + file, e);
|
||||
}
|
||||
}
|
||||
return accessKey;
|
||||
}
|
||||
|
||||
public String resolvedSecretKey() {
|
||||
var file = System.getenv("S3_SECRET_ACCESS_KEY_FILE");
|
||||
if (file != null && !file.isBlank()) {
|
||||
try {
|
||||
return new String(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(file)))
|
||||
.strip();
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("Failed to read S3_SECRET_ACCESS_KEY_FILE: " + file, e);
|
||||
}
|
||||
}
|
||||
return secretKey;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package ru.mtusi.messenger.config.properties;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
import java.time.Duration;
|
||||
|
||||
@ConfigurationProperties(prefix = "app.session")
|
||||
public record SessionProperties(Duration ttl) {}
|
||||
@@ -0,0 +1,12 @@
|
||||
package ru.mtusi.messenger.config.properties;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.boot.context.properties.bind.DefaultValue;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@ConfigurationProperties(prefix = "upload")
|
||||
public record UploadProperties(
|
||||
@DefaultValue("10485760") long maxBytes,
|
||||
@DefaultValue("40000000") long maxPixels,
|
||||
@DefaultValue({"image/png", "image/jpeg"}) List<String> allowedContentTypes) {}
|
||||
@@ -0,0 +1,43 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import ru.mtusi.messenger.dto.AttachmentDTO;
|
||||
import ru.mtusi.messenger.security.SessionPrincipal;
|
||||
import ru.mtusi.messenger.service.AttachmentService;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class AttachmentController implements AttachmentsApi {
|
||||
private final AttachmentService service;
|
||||
|
||||
@Override
|
||||
public AttachmentDTO uploadAttachment(
|
||||
UUID chatId,
|
||||
String filename,
|
||||
HttpServletRequest body,
|
||||
String contentType,
|
||||
@AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return service.upload(chatId, principal.userId(), filename, body, contentType);
|
||||
}
|
||||
|
||||
@Override
|
||||
public AttachmentDTO getAttachment(
|
||||
UUID attachmentId, @AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return service.getMetadata(attachmentId, principal.userId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public ResponseEntity<byte[]> downloadAttachment(
|
||||
UUID attachmentId, String variant, SessionPrincipal principal) {
|
||||
return service.downloadResponse(attachmentId, principal.userId(), variant);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,314 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.hibernate.validator.constraints.CodePointLength;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
import ru.mtusi.messenger.dto.AttachmentDTO;
|
||||
import ru.mtusi.messenger.dto.ErrorDTO;
|
||||
import ru.mtusi.messenger.security.SessionPrincipal;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/** HTTP-контракт; валидация и описание операций отделены от реализации. */
|
||||
@Validated
|
||||
@Tag(name = "Attachments", description = "Загрузка и скачивание вложений (PNG/JPEG) в чатах.")
|
||||
@RequestMapping("${openapi.mTUSIMessenger2.base-path:}")
|
||||
public interface AttachmentsApi {
|
||||
|
||||
/**
|
||||
* Принимает PNG/JPEG до 10 MiB для участника чата. Возвращает 202 queued только после
|
||||
* сохранения исходника и COMMIT вложения, задания и outbox; обработка выполняется отдельно.
|
||||
*/
|
||||
@Operation(
|
||||
operationId = "uploadAttachment",
|
||||
summary = "Принять один PNG/JPEG, до 10 MiB",
|
||||
tags = {"Attachments"},
|
||||
responses = {
|
||||
@ApiResponse(
|
||||
responseCode = "202",
|
||||
description = "Успех",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = AttachmentDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "400",
|
||||
description = "Неверный запрос",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "401",
|
||||
description = "Нет действительной аутентификации",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "404",
|
||||
description = "Объект отсутствует или недоступен",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "413",
|
||||
description = "Превышен лимит",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "415",
|
||||
description = "Неподдерживаемый тип",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "429",
|
||||
description = "Ограничение частоты запросов",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "503",
|
||||
description = "Зависимость недоступна",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = {@SecurityRequirement(name = "bearerAuth")})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.POST,
|
||||
value = "/api/v1/chats/{chat_id}/attachments",
|
||||
consumes = {MediaType.IMAGE_PNG_VALUE, MediaType.IMAGE_JPEG_VALUE},
|
||||
produces = {MediaType.APPLICATION_JSON_VALUE})
|
||||
@ResponseStatus(org.springframework.http.HttpStatus.ACCEPTED)
|
||||
AttachmentDTO uploadAttachment(
|
||||
@Parameter(name = "chat_id", required = true, in = ParameterIn.PATH)
|
||||
@PathVariable("chat_id")
|
||||
UUID chatId,
|
||||
@Parameter(name = "filename", required = true, in = ParameterIn.QUERY)
|
||||
@CodePointLength(min = 1, max = 255)
|
||||
@RequestParam("filename")
|
||||
String filename,
|
||||
HttpServletRequest body,
|
||||
@RequestHeader("Content-Type") String contentType,
|
||||
@AuthenticationPrincipal SessionPrincipal principal);
|
||||
|
||||
/** Возвращает согласованный снимок вложения; варианты доступны только в состоянии ready. */
|
||||
@Operation(
|
||||
operationId = "getAttachment",
|
||||
summary = "Метаданные вложения, доступ участникам чата",
|
||||
tags = {"Attachments"},
|
||||
responses = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "Успех",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = AttachmentDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "400",
|
||||
description = "Неверный запрос",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "401",
|
||||
description = "Нет действительной аутентификации",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "404",
|
||||
description = "Объект отсутствует или недоступен",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "409",
|
||||
description = "Конфликт",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "429",
|
||||
description = "Ограничение частоты запросов",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "503",
|
||||
description = "Зависимость недоступна",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = {@SecurityRequirement(name = "bearerAuth")})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.GET,
|
||||
value = "/api/v1/attachments/{attachment_id}",
|
||||
produces = {MediaType.APPLICATION_JSON_VALUE})
|
||||
@ResponseStatus(org.springframework.http.HttpStatus.OK)
|
||||
AttachmentDTO getAttachment(
|
||||
@Parameter(name = "attachment_id", required = true, in = ParameterIn.PATH)
|
||||
@PathVariable("attachment_id")
|
||||
UUID attachmentId,
|
||||
@AuthenticationPrincipal SessionPrincipal principal);
|
||||
|
||||
/**
|
||||
* Возвращает байты выбранного варианта участнику чата; до ready отвечает 409 без редиректа в
|
||||
* S3.
|
||||
*/
|
||||
@Operation(
|
||||
operationId = "downloadAttachment",
|
||||
summary = "Скачать байты через авторизованный API",
|
||||
tags = {"Attachments"},
|
||||
responses = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "Успех",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "image/png",
|
||||
schema = @Schema(type = "string", format = "binary")),
|
||||
@Content(
|
||||
mediaType = "image/jpeg",
|
||||
schema = @Schema(type = "string", format = "binary")),
|
||||
@Content(
|
||||
mediaType = "image/webp",
|
||||
schema = @Schema(type = "string", format = "binary"))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "400",
|
||||
description = "Неверный запрос",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "401",
|
||||
description = "Нет действительной аутентификации",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "404",
|
||||
description = "Объект отсутствует или недоступен",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "409",
|
||||
description = "Конфликт",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "429",
|
||||
description = "Ограничение частоты запросов",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "503",
|
||||
description = "Зависимость недоступна",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = {@SecurityRequirement(name = "bearerAuth")})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.GET,
|
||||
value = "/api/v1/attachments/{attachment_id}/content")
|
||||
ResponseEntity<byte[]> downloadAttachment(
|
||||
@Parameter(name = "attachment_id", required = true, in = ParameterIn.PATH)
|
||||
@PathVariable("attachment_id")
|
||||
UUID attachmentId,
|
||||
@Parameter(name = "variant", in = ParameterIn.QUERY)
|
||||
@RequestParam(value = "variant", required = false, defaultValue = "original")
|
||||
String variant,
|
||||
@AuthenticationPrincipal SessionPrincipal principal);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
import ru.mtusi.messenger.dto.ErrorDTO;
|
||||
import ru.mtusi.messenger.dto.SessionDTO;
|
||||
|
||||
/** HTTP-контракт; валидация и описание операций отделены от реализации. */
|
||||
@Validated
|
||||
@Tag(
|
||||
name = "Auth",
|
||||
description = "Аутентификация: вход по Basic и выдача/отзыв сессионного Bearer-токена.")
|
||||
@RequestMapping("${openapi.mTUSIMessenger2.base-path:}")
|
||||
public interface AuthApi {
|
||||
|
||||
/** Вход: Basic username:password; выдаёт сессию. */
|
||||
@Operation(
|
||||
operationId = "createSession",
|
||||
summary = "Вход: Basic username:password; выдаёт сессию",
|
||||
tags = {"Auth"},
|
||||
responses = {
|
||||
@ApiResponse(
|
||||
responseCode = "201",
|
||||
description = "Успех",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = SessionDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "400",
|
||||
description = "Неверный запрос",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "401",
|
||||
description = "Нет действительной аутентификации",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "429",
|
||||
description = "Ограничение частоты запросов",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "503",
|
||||
description = "Зависимость недоступна",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = {@SecurityRequirement(name = "basicAuth")})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.POST,
|
||||
value = "/api/v1/auth/sessions",
|
||||
produces = {"application/json"})
|
||||
@ResponseStatus(org.springframework.http.HttpStatus.CREATED)
|
||||
SessionDTO createSession(HttpServletRequest request);
|
||||
|
||||
/** Отозвать текущую сессию. */
|
||||
@Operation(
|
||||
operationId = "revokeSession",
|
||||
summary = "Отозвать текущую сессию",
|
||||
tags = {"Auth"},
|
||||
responses = {
|
||||
@ApiResponse(responseCode = "204", description = "Успех"),
|
||||
@ApiResponse(
|
||||
responseCode = "401",
|
||||
description = "Нет действительной аутентификации",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "429",
|
||||
description = "Ограничение частоты запросов",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "503",
|
||||
description = "Зависимость недоступна",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = {@SecurityRequirement(name = "bearerAuth")})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.DELETE,
|
||||
value = "/api/v1/auth/sessions/current",
|
||||
produces = {"application/json"})
|
||||
@ResponseStatus(org.springframework.http.HttpStatus.NO_CONTENT)
|
||||
void revokeSession();
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import ru.mtusi.messenger.dto.SessionDTO;
|
||||
import ru.mtusi.messenger.service.AuthService;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class AuthController implements AuthApi {
|
||||
private final AuthService authService;
|
||||
|
||||
@Override
|
||||
public SessionDTO createSession(HttpServletRequest request) {
|
||||
return authService.login(
|
||||
request.getHeader(HttpHeaders.AUTHORIZATION), request.getContentLengthLong());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void revokeSession() {
|
||||
authService.logout();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import ru.mtusi.messenger.dto.ChatDTO;
|
||||
import ru.mtusi.messenger.dto.ChatPageDTO;
|
||||
import ru.mtusi.messenger.dto.CreateChatDTO;
|
||||
import ru.mtusi.messenger.security.SessionPrincipal;
|
||||
import ru.mtusi.messenger.service.ChatService;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class ChatController implements ChatsApi {
|
||||
private final ChatService chatService;
|
||||
|
||||
@Override
|
||||
public ChatDTO createChat(
|
||||
CreateChatDTO createChatDTO, @AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return chatService.createChat(principal.userId(), createChatDTO);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatDTO getChat(UUID chatId, @AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return chatService.getChatDTO(principal.userId(), chatId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ChatPageDTO listChats(
|
||||
Integer limit, String cursor, @AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return chatService.listChats(principal.userId(), limit, cursor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
import ru.mtusi.messenger.dto.ChatDTO;
|
||||
import ru.mtusi.messenger.dto.ChatPageDTO;
|
||||
import ru.mtusi.messenger.dto.CreateChatDTO;
|
||||
import ru.mtusi.messenger.dto.ErrorDTO;
|
||||
import ru.mtusi.messenger.security.SessionPrincipal;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/** HTTP-контракт; валидация и описание операций отделены от реализации. */
|
||||
@Validated
|
||||
@Tag(name = "Chats", description = "Управление чатами и доступ к чатам текущего пользователя.")
|
||||
@RequestMapping("${openapi.mTUSIMessenger2.base-path:}")
|
||||
public interface ChatsApi {
|
||||
|
||||
/** Создать чат; вызывающий должен входить в member_ids. */
|
||||
@Operation(
|
||||
operationId = "createChat",
|
||||
summary = "Создать чат; вызывающий должен входить в member_ids",
|
||||
tags = {"Chats"},
|
||||
responses = {
|
||||
@ApiResponse(
|
||||
responseCode = "201",
|
||||
description = "Успех",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ChatDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "400",
|
||||
description = "Неверный запрос",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "401",
|
||||
description = "Нет действительной аутентификации",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "404",
|
||||
description = "Объект отсутствует или недоступен",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "409",
|
||||
description = "Конфликт",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "429",
|
||||
description = "Ограничение частоты запросов",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "503",
|
||||
description = "Зависимость недоступна",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = {@SecurityRequirement(name = "bearerAuth")})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.POST,
|
||||
value = "/api/v1/chats",
|
||||
produces = {"application/json"},
|
||||
consumes = {"application/json"})
|
||||
@ResponseStatus(org.springframework.http.HttpStatus.CREATED)
|
||||
ChatDTO createChat(
|
||||
@Parameter(name = "CreateChatDTO", description = "", required = true)
|
||||
@Valid
|
||||
@RequestBody
|
||||
CreateChatDTO createChatDTO,
|
||||
@AuthenticationPrincipal SessionPrincipal principal);
|
||||
|
||||
/** Получить доступный чат. */
|
||||
@Operation(
|
||||
operationId = "getChatDTO",
|
||||
summary = "Получить доступный чат",
|
||||
tags = {"Chats"},
|
||||
responses = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "Успех",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ChatDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "400",
|
||||
description = "Неверный запрос",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "401",
|
||||
description = "Нет действительной аутентификации",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "404",
|
||||
description = "Объект отсутствует или недоступен",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "409",
|
||||
description = "Конфликт",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "429",
|
||||
description = "Ограничение частоты запросов",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "503",
|
||||
description = "Зависимость недоступна",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = {@SecurityRequirement(name = "bearerAuth")})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.GET,
|
||||
value = "/api/v1/chats/{chat_id}",
|
||||
produces = {"application/json"})
|
||||
@ResponseStatus(org.springframework.http.HttpStatus.OK)
|
||||
ChatDTO getChat(
|
||||
@Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH)
|
||||
@PathVariable("chat_id")
|
||||
UUID chatId,
|
||||
@AuthenticationPrincipal SessionPrincipal principal);
|
||||
|
||||
/** Чаты текущего пользователя. */
|
||||
@Operation(
|
||||
operationId = "listChats",
|
||||
summary = "Чаты текущего пользователя",
|
||||
tags = {"Chats"},
|
||||
responses = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "Успех",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ChatPageDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "400",
|
||||
description = "Неверный запрос",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "401",
|
||||
description = "Нет действительной аутентификации",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "404",
|
||||
description = "Объект отсутствует или недоступен",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "409",
|
||||
description = "Конфликт",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "429",
|
||||
description = "Ограничение частоты запросов",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "503",
|
||||
description = "Зависимость недоступна",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = {@SecurityRequirement(name = "bearerAuth")})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.GET,
|
||||
value = "/api/v1/chats",
|
||||
produces = {"application/json"})
|
||||
@ResponseStatus(org.springframework.http.HttpStatus.OK)
|
||||
ChatPageDTO listChats(
|
||||
@Min(1)
|
||||
@Max(100)
|
||||
@Parameter(name = "limit", description = "", in = ParameterIn.QUERY)
|
||||
@Valid
|
||||
@RequestParam(value = "limit", required = false, defaultValue = "50")
|
||||
Integer limit,
|
||||
@Size(min = 1)
|
||||
@Parameter(name = "cursor", description = "", in = ParameterIn.QUERY)
|
||||
@Valid
|
||||
@RequestParam(value = "cursor", required = false)
|
||||
String cursor,
|
||||
@AuthenticationPrincipal SessionPrincipal principal);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
import ru.mtusi.messenger.dto.ErrorDTO;
|
||||
import ru.mtusi.messenger.dto.HealthDTO;
|
||||
|
||||
/** HTTP-контракт; валидация и описание операций отделены от реализации. */
|
||||
@Validated
|
||||
@Tag(
|
||||
name = "Health",
|
||||
description = "Проверки живости и готовности процесса. Публичные, без аутентификации.")
|
||||
@RequestMapping("${openapi.mTUSIMessenger2.base-path:}")
|
||||
public interface HealthApi {
|
||||
|
||||
/** Процесс жив. */
|
||||
@Operation(
|
||||
operationId = "liveness",
|
||||
summary = "Процесс жив",
|
||||
tags = {"Health"},
|
||||
responses = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "Успех",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = HealthDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.GET,
|
||||
value = "/health/live",
|
||||
produces = {"application/json"})
|
||||
@ResponseStatus(org.springframework.http.HttpStatus.OK)
|
||||
HealthDTO liveness();
|
||||
|
||||
/** Готов принимать трафик. */
|
||||
@Operation(
|
||||
operationId = "readiness",
|
||||
summary = "Готов принимать трафик",
|
||||
tags = {"Health"},
|
||||
responses = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "Успех",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = HealthDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "503",
|
||||
description = "Зависимость недоступна",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.GET,
|
||||
value = "/health/ready",
|
||||
produces = {"application/json"})
|
||||
@ResponseStatus(org.springframework.http.HttpStatus.OK)
|
||||
HealthDTO readiness();
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import ru.mtusi.messenger.dto.HealthDTO;
|
||||
import ru.mtusi.messenger.service.HealthService;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class HealthController implements HealthApi {
|
||||
private final HealthService healthService;
|
||||
|
||||
@Override
|
||||
public HealthDTO liveness() {
|
||||
return healthService.liveness();
|
||||
}
|
||||
|
||||
@Override
|
||||
public HealthDTO readiness() {
|
||||
return healthService.readiness();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import ru.mtusi.messenger.dto.CreateMessageDTO;
|
||||
import ru.mtusi.messenger.dto.MessageDTO;
|
||||
import ru.mtusi.messenger.dto.MessagePageDTO;
|
||||
import ru.mtusi.messenger.security.SessionPrincipal;
|
||||
import ru.mtusi.messenger.service.MessageService;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class MessageController implements MessagesApi {
|
||||
private final MessageService messageService;
|
||||
|
||||
@Override
|
||||
public MessageDTO createMessage(
|
||||
UUID chatId,
|
||||
String idempotencyKey,
|
||||
CreateMessageDTO createMessageDTO,
|
||||
@AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return messageService.createMessage(
|
||||
principal.userId(), chatId, createMessageDTO, idempotencyKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
public MessagePageDTO listMessages(
|
||||
UUID chatId,
|
||||
Integer limit,
|
||||
String cursor,
|
||||
@AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return messageService.listMessages(principal.userId(), chatId, limit, cursor);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
import ru.mtusi.messenger.dto.CreateMessageDTO;
|
||||
import ru.mtusi.messenger.dto.ErrorDTO;
|
||||
import ru.mtusi.messenger.dto.MessageDTO;
|
||||
import ru.mtusi.messenger.dto.MessagePageDTO;
|
||||
import ru.mtusi.messenger.security.SessionPrincipal;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
/** HTTP-контракт; валидация и описание операций отделены от реализации. */
|
||||
@Validated
|
||||
@Tag(name = "Messages", description = "Отправка и чтение сообщений внутри доступного чата.")
|
||||
@RequestMapping("${openapi.mTUSIMessenger2.base-path:}")
|
||||
public interface MessagesApi {
|
||||
|
||||
/**
|
||||
* Создаёт сообщение идемпотентно в пределах пользователя и чата. Повтор ключа с другим телом
|
||||
* даёт 409; queued/processing вложения допустимы, failed отклоняются до COMMIT сообщения.
|
||||
*/
|
||||
@Operation(
|
||||
operationId = "createMessage",
|
||||
summary = "Отправить сообщение",
|
||||
tags = {"Messages"},
|
||||
responses = {
|
||||
@ApiResponse(
|
||||
responseCode = "201",
|
||||
description = "Успех",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = MessageDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "400",
|
||||
description = "Неверный запрос",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "401",
|
||||
description = "Нет действительной аутентификации",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "404",
|
||||
description = "Объект отсутствует или недоступен",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "409",
|
||||
description = "Конфликт",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "429",
|
||||
description = "Ограничение частоты запросов",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "503",
|
||||
description = "Зависимость недоступна",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = {@SecurityRequirement(name = "bearerAuth")})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.POST,
|
||||
value = "/api/v1/chats/{chat_id}/messages",
|
||||
produces = {"application/json"},
|
||||
consumes = {"application/json"})
|
||||
@ResponseStatus(org.springframework.http.HttpStatus.CREATED)
|
||||
MessageDTO createMessage(
|
||||
@Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH)
|
||||
@PathVariable("chat_id")
|
||||
UUID chatId,
|
||||
@Parameter(name = "Idempotency-Key", required = true, in = ParameterIn.HEADER)
|
||||
@RequestHeader(value = "Idempotency-Key", required = true)
|
||||
String idempotencyKey,
|
||||
@Parameter(name = "CreateMessageDTO", description = "", required = true)
|
||||
@Valid
|
||||
@RequestBody
|
||||
CreateMessageDTO createMessageDTO,
|
||||
@AuthenticationPrincipal SessionPrincipal principal);
|
||||
|
||||
/** Сообщения по (created_at, id) по возрастанию. */
|
||||
@Operation(
|
||||
operationId = "listMessages",
|
||||
summary = "Сообщения по (created_at, id) по возрастанию",
|
||||
tags = {"Messages"},
|
||||
responses = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "Успех",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = MessagePageDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "400",
|
||||
description = "Неверный запрос",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "401",
|
||||
description = "Нет действительной аутентификации",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "404",
|
||||
description = "Объект отсутствует или недоступен",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "409",
|
||||
description = "Конфликт",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "429",
|
||||
description = "Ограничение частоты запросов",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "503",
|
||||
description = "Зависимость недоступна",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = {@SecurityRequirement(name = "bearerAuth")})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.GET,
|
||||
value = "/api/v1/chats/{chat_id}/messages",
|
||||
produces = {"application/json"})
|
||||
@ResponseStatus(org.springframework.http.HttpStatus.OK)
|
||||
MessagePageDTO listMessages(
|
||||
@Parameter(name = "chat_id", description = "", required = true, in = ParameterIn.PATH)
|
||||
@PathVariable("chat_id")
|
||||
UUID chatId,
|
||||
@Min(1)
|
||||
@Max(100)
|
||||
@Parameter(name = "limit", description = "", in = ParameterIn.QUERY)
|
||||
@Valid
|
||||
@RequestParam(value = "limit", required = false, defaultValue = "50")
|
||||
Integer limit,
|
||||
@Size(min = 1)
|
||||
@Parameter(name = "cursor", description = "", in = ParameterIn.QUERY)
|
||||
@Valid
|
||||
@RequestParam(value = "cursor", required = false)
|
||||
String cursor,
|
||||
@AuthenticationPrincipal SessionPrincipal principal);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import ru.mtusi.messenger.dto.CreateUserDTO;
|
||||
import ru.mtusi.messenger.dto.UserDTO;
|
||||
import ru.mtusi.messenger.security.SessionPrincipal;
|
||||
import ru.mtusi.messenger.service.UserService;
|
||||
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class UserController implements UsersApi {
|
||||
private final UserService userService;
|
||||
|
||||
@Override
|
||||
public UserDTO currentUser(@AuthenticationPrincipal SessionPrincipal principal) {
|
||||
return userService.currentUser(principal.userId());
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDTO registerUser(CreateUserDTO createUserDTO) {
|
||||
return userService.registerUser(createUserDTO);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
package ru.mtusi.messenger.controller;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.responses.ApiResponse;
|
||||
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
import ru.mtusi.messenger.dto.CreateUserDTO;
|
||||
import ru.mtusi.messenger.dto.ErrorDTO;
|
||||
import ru.mtusi.messenger.dto.UserDTO;
|
||||
import ru.mtusi.messenger.security.SessionPrincipal;
|
||||
|
||||
/** HTTP-контракт; валидация и описание операций отделены от реализации. */
|
||||
@Validated
|
||||
@Tag(
|
||||
name = "Users",
|
||||
description = "Регистрация пользователей и доступ к профилю текущего пользователя.")
|
||||
@RequestMapping("${openapi.mTUSIMessenger2.base-path:}")
|
||||
public interface UsersApi {
|
||||
|
||||
/** Текущий пользователь. */
|
||||
@Operation(
|
||||
operationId = "currentUser",
|
||||
summary = "Текущий пользователь",
|
||||
tags = {"Users"},
|
||||
responses = {
|
||||
@ApiResponse(
|
||||
responseCode = "200",
|
||||
description = "Успех",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = UserDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "400",
|
||||
description = "Неверный запрос",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "401",
|
||||
description = "Нет действительной аутентификации",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "404",
|
||||
description = "Объект отсутствует или недоступен",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "409",
|
||||
description = "Конфликт",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "429",
|
||||
description = "Ограничение частоты запросов",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "503",
|
||||
description = "Зависимость недоступна",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
},
|
||||
security = {@SecurityRequirement(name = "bearerAuth")})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.GET,
|
||||
value = "/api/v1/users/me",
|
||||
produces = {"application/json"})
|
||||
@ResponseStatus(org.springframework.http.HttpStatus.OK)
|
||||
UserDTO currentUser(@AuthenticationPrincipal SessionPrincipal principal);
|
||||
|
||||
/** Создать пользователя. */
|
||||
@Operation(
|
||||
operationId = "registerUser",
|
||||
summary = "Создать пользователя",
|
||||
tags = {"Users"},
|
||||
responses = {
|
||||
@ApiResponse(
|
||||
responseCode = "201",
|
||||
description = "Успех",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = UserDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "400",
|
||||
description = "Неверный запрос",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "409",
|
||||
description = "Конфликт",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "429",
|
||||
description = "Ограничение частоты запросов",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "503",
|
||||
description = "Зависимость недоступна",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
}),
|
||||
@ApiResponse(
|
||||
responseCode = "500",
|
||||
description = "Неожиданная ошибка без внутренних деталей",
|
||||
content = {
|
||||
@Content(
|
||||
mediaType = "application/json",
|
||||
schema = @Schema(implementation = ErrorDTO.class))
|
||||
})
|
||||
})
|
||||
@RequestMapping(
|
||||
method = RequestMethod.POST,
|
||||
value = "/api/v1/users",
|
||||
produces = {"application/json"},
|
||||
consumes = {"application/json"})
|
||||
@ResponseStatus(org.springframework.http.HttpStatus.CREATED)
|
||||
UserDTO registerUser(
|
||||
@Parameter(name = "CreateUserDTO", description = "", required = true)
|
||||
@Valid
|
||||
@RequestBody
|
||||
CreateUserDTO createUserDTO);
|
||||
}
|
||||
+247
@@ -0,0 +1,247 @@
|
||||
package ru.mtusi.messenger.controller.controllerAdvice;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.dao.DataAccessResourceFailureException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.transaction.CannotCreateTransactionException;
|
||||
import org.springframework.web.HttpMediaTypeNotSupportedException;
|
||||
import org.springframework.web.HttpRequestMethodNotSupportedException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.MissingRequestHeaderException;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.method.annotation.HandlerMethodValidationException;
|
||||
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
|
||||
|
||||
import ru.mtusi.messenger.config.properties.RateLimitProperties;
|
||||
import ru.mtusi.messenger.dto.ErrorDTO;
|
||||
import ru.mtusi.messenger.dto.ErrorErrorDTO;
|
||||
import ru.mtusi.messenger.exception.ApiErrorFactory;
|
||||
import ru.mtusi.messenger.exception.ConflictException;
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
import ru.mtusi.messenger.exception.NotFoundException;
|
||||
import ru.mtusi.messenger.exception.PayloadTooLargeException;
|
||||
import ru.mtusi.messenger.exception.RateLimitedException;
|
||||
import ru.mtusi.messenger.exception.ServiceUnavailableException;
|
||||
import ru.mtusi.messenger.exception.StorageUnavailableException;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.exception.UnsupportedMediaTypeException;
|
||||
|
||||
@RestControllerAdvice
|
||||
@RequiredArgsConstructor
|
||||
public class GlobalExceptionHandler {
|
||||
private static final org.slf4j.Logger log =
|
||||
org.slf4j.LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
private final RateLimitProperties limitProperties;
|
||||
private final ApiErrorFactory errors;
|
||||
|
||||
@ExceptionHandler(InvalidRequestException.class)
|
||||
public ResponseEntity<ErrorDTO> invalidRequest(
|
||||
InvalidRequestException e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
|
||||
e.getMessage(),
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UnauthorizedException.class)
|
||||
public ResponseEntity<ErrorDTO> unauthorized(UnauthorizedException e, HttpServletRequest req) {
|
||||
boolean isLogin = "/api/v1/auth/sessions".equals(req.getRequestURI());
|
||||
String challenge =
|
||||
isLogin
|
||||
? "Basic realm=\"messenger\", charset=\"UTF-8\""
|
||||
: "Bearer realm=\"messenger\"";
|
||||
return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
|
||||
.header("WWW-Authenticate", challenge)
|
||||
.body(errors.error(ErrorErrorDTO.CodeEnum.UNAUTHORIZED, e.getMessage(), req));
|
||||
}
|
||||
|
||||
@ExceptionHandler(NotFoundException.class)
|
||||
public ResponseEntity<ErrorDTO> notFound(NotFoundException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.NOT_FOUND, ErrorErrorDTO.CodeEnum.NOT_FOUND, e.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConflictException.class)
|
||||
public ResponseEntity<ErrorDTO> conflict(ConflictException e, HttpServletRequest req) {
|
||||
return respond(HttpStatus.CONFLICT, ErrorErrorDTO.CodeEnum.CONFLICT, e.getMessage(), req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(PayloadTooLargeException.class)
|
||||
public ResponseEntity<ErrorDTO> payloadTooLarge(
|
||||
PayloadTooLargeException e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.PAYLOAD_TOO_LARGE,
|
||||
ErrorErrorDTO.CodeEnum.PAYLOAD_TOO_LARGE,
|
||||
e.getMessage(),
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<ErrorDTO> validation(
|
||||
MethodArgumentNotValidException e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
|
||||
"Validation failed",
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
public ResponseEntity<ErrorDTO> unreadable(Exception e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
|
||||
"Malformed request body",
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MissingServletRequestParameterException.class)
|
||||
public ResponseEntity<ErrorDTO> missingParam(Exception e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
|
||||
"Missing parameter",
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
|
||||
public ResponseEntity<ErrorDTO> typeMismatch(Exception e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
|
||||
"Invalid parameter type",
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpMediaTypeNotSupportedException.class)
|
||||
public ResponseEntity<ErrorDTO> mediaType(Exception e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.UNSUPPORTED_MEDIA_TYPE,
|
||||
ErrorErrorDTO.CodeEnum.UNSUPPORTED_MEDIA_TYPE,
|
||||
"Unsupported media type",
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HandlerMethodValidationException.class)
|
||||
public ResponseEntity<ErrorDTO> methodValidation(Exception e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
|
||||
"Validation failed",
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
|
||||
public ResponseEntity<ErrorDTO> methodNotAllowed(Exception e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.METHOD_NOT_ALLOWED,
|
||||
ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
|
||||
"Method not allowed",
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(RateLimitedException.class)
|
||||
public ResponseEntity<ErrorDTO> rateLimited(RateLimitedException e, HttpServletRequest req) {
|
||||
return ResponseEntity.status(HttpStatus.TOO_MANY_REQUESTS)
|
||||
.header("Retry-After", String.valueOf(limitProperties.retryAfterSeconds()))
|
||||
.body(errors.error(ErrorErrorDTO.CodeEnum.RATE_LIMITED, e.getMessage(), req));
|
||||
}
|
||||
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public ResponseEntity<ErrorDTO> constraint(
|
||||
ConstraintViolationException e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
|
||||
"Validation failed",
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorDTO> fallback(Exception e, HttpServletRequest req) {
|
||||
log.error("Unexpected API failure type={}", e.getClass().getName());
|
||||
return respond(
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
ErrorErrorDTO.CodeEnum.INTERNAL_ERROR,
|
||||
"Internal error",
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(ServiceUnavailableException.class)
|
||||
public ResponseEntity<ErrorDTO> serviceUnavailable(
|
||||
ServiceUnavailableException e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
ErrorErrorDTO.CodeEnum.UNAVAILABLE,
|
||||
e.getMessage(),
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler({
|
||||
CannotCreateTransactionException.class,
|
||||
DataAccessResourceFailureException.class
|
||||
})
|
||||
public ResponseEntity<ErrorDTO> dependencyUnavailable(Exception e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
ErrorErrorDTO.CodeEnum.UNAVAILABLE,
|
||||
"Dependency unavailable",
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(DataAccessException.class)
|
||||
public ResponseEntity<ErrorDTO> dataAccess(DataAccessException e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
ErrorErrorDTO.CodeEnum.INTERNAL_ERROR,
|
||||
"Database error",
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MissingRequestHeaderException.class)
|
||||
public ResponseEntity<ErrorDTO> missingHeader(
|
||||
MissingRequestHeaderException e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.BAD_REQUEST,
|
||||
ErrorErrorDTO.CodeEnum.INVALID_REQUEST,
|
||||
"Missing header: " + e.getHeaderName(),
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(UnsupportedMediaTypeException.class)
|
||||
public ResponseEntity<ErrorDTO> unsupportedMedia(
|
||||
UnsupportedMediaTypeException e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.UNSUPPORTED_MEDIA_TYPE,
|
||||
ErrorErrorDTO.CodeEnum.UNSUPPORTED_MEDIA_TYPE,
|
||||
e.getMessage(),
|
||||
req);
|
||||
}
|
||||
|
||||
@ExceptionHandler(StorageUnavailableException.class)
|
||||
public ResponseEntity<ErrorDTO> storageUnavailable(
|
||||
StorageUnavailableException e, HttpServletRequest req) {
|
||||
return respond(
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
ErrorErrorDTO.CodeEnum.UNAVAILABLE,
|
||||
e.getMessage(),
|
||||
req);
|
||||
}
|
||||
|
||||
private ResponseEntity<ErrorDTO> respond(
|
||||
HttpStatus status,
|
||||
ErrorErrorDTO.CodeEnum code,
|
||||
String message,
|
||||
HttpServletRequest req) {
|
||||
return ResponseEntity.status(status).body(errors.error(code, message, req));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,417 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.annotation.Generated;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.Max;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
@Generated(
|
||||
value = "org.openapitools.codegen.languages.SpringCodegen",
|
||||
comments = "Generator version: 7.10.0")
|
||||
public class AttachmentDTO {
|
||||
|
||||
private UUID id;
|
||||
|
||||
private UUID chatId;
|
||||
|
||||
private UUID ownerId;
|
||||
|
||||
private String filename;
|
||||
|
||||
public enum ContentTypeEnum {
|
||||
IMAGE_PNG("image/png"),
|
||||
IMAGE_JPEG("image/jpeg");
|
||||
|
||||
private final String value;
|
||||
|
||||
ContentTypeEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static ContentTypeEnum fromValue(String value) {
|
||||
for (ContentTypeEnum b : ContentTypeEnum.values()) {
|
||||
if (b.value.equals(value)) {
|
||||
return b;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unexpected value '" + value + "'");
|
||||
}
|
||||
}
|
||||
|
||||
private ContentTypeEnum contentType;
|
||||
|
||||
private Long sizeBytes;
|
||||
|
||||
private String sha256;
|
||||
|
||||
public enum StatusEnum {
|
||||
QUEUED("queued"),
|
||||
PROCESSING("processing"),
|
||||
READY("ready"),
|
||||
FAILED("failed");
|
||||
|
||||
private final String value;
|
||||
|
||||
StatusEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static StatusEnum fromValue(String value) {
|
||||
for (StatusEnum b : StatusEnum.values()) {
|
||||
if (b.value.equals(value)) {
|
||||
return b;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unexpected value '" + value + "'");
|
||||
}
|
||||
}
|
||||
|
||||
private StatusEnum status;
|
||||
|
||||
@Valid private List<@Valid VariantDTO> variants = new ArrayList<>();
|
||||
|
||||
private String errorCode;
|
||||
|
||||
private Instant createdAt;
|
||||
|
||||
private Instant updatedAt;
|
||||
|
||||
public AttachmentDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public AttachmentDTO(
|
||||
UUID id,
|
||||
UUID chatId,
|
||||
UUID ownerId,
|
||||
String filename,
|
||||
ContentTypeEnum contentType,
|
||||
Long sizeBytes,
|
||||
String sha256,
|
||||
StatusEnum status,
|
||||
List<@Valid VariantDTO> variants,
|
||||
String errorCode,
|
||||
Instant createdAt,
|
||||
Instant updatedAt) {
|
||||
this.id = id;
|
||||
this.chatId = chatId;
|
||||
this.ownerId = ownerId;
|
||||
this.filename = filename;
|
||||
this.contentType = contentType;
|
||||
this.sizeBytes = sizeBytes;
|
||||
this.sha256 = sha256;
|
||||
this.status = status;
|
||||
this.variants = variants;
|
||||
this.errorCode = errorCode;
|
||||
this.createdAt = createdAt;
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public AttachmentDTO id(UUID id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@Schema(name = "id", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("id")
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public AttachmentDTO chatId(UUID chatId) {
|
||||
this.chatId = chatId;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@Schema(name = "chat_id", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("chat_id")
|
||||
public UUID getChatId() {
|
||||
return chatId;
|
||||
}
|
||||
|
||||
public void setChatId(UUID chatId) {
|
||||
this.chatId = chatId;
|
||||
}
|
||||
|
||||
public AttachmentDTO ownerId(UUID ownerId) {
|
||||
this.ownerId = ownerId;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@Schema(name = "owner_id", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("owner_id")
|
||||
public UUID getOwnerId() {
|
||||
return ownerId;
|
||||
}
|
||||
|
||||
public void setOwnerId(UUID ownerId) {
|
||||
this.ownerId = ownerId;
|
||||
}
|
||||
|
||||
public AttachmentDTO filename(String filename) {
|
||||
this.filename = filename;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Size(min = 1, max = 255)
|
||||
@Schema(name = "filename", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("filename")
|
||||
public String getFilename() {
|
||||
return filename;
|
||||
}
|
||||
|
||||
public void setFilename(String filename) {
|
||||
this.filename = filename;
|
||||
}
|
||||
|
||||
public AttachmentDTO contentType(ContentTypeEnum contentType) {
|
||||
this.contentType = contentType;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Schema(name = "content_type", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("content_type")
|
||||
public ContentTypeEnum getContentType() {
|
||||
return contentType;
|
||||
}
|
||||
|
||||
public void setContentType(ContentTypeEnum contentType) {
|
||||
this.contentType = contentType;
|
||||
}
|
||||
|
||||
public AttachmentDTO sizeBytes(Long sizeBytes) {
|
||||
this.sizeBytes = sizeBytes;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Min(1L)
|
||||
@Max(10485760L)
|
||||
@Schema(name = "size_bytes", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("size_bytes")
|
||||
public Long getSizeBytes() {
|
||||
return sizeBytes;
|
||||
}
|
||||
|
||||
public void setSizeBytes(Long sizeBytes) {
|
||||
this.sizeBytes = sizeBytes;
|
||||
}
|
||||
|
||||
public AttachmentDTO sha256(String sha256) {
|
||||
this.sha256 = sha256;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Pattern(regexp = "^[a-f0-9]{64}$")
|
||||
@Schema(name = "sha256", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("sha256")
|
||||
public String getSha256() {
|
||||
return sha256;
|
||||
}
|
||||
|
||||
public void setSha256(String sha256) {
|
||||
this.sha256 = sha256;
|
||||
}
|
||||
|
||||
public AttachmentDTO status(StatusEnum status) {
|
||||
this.status = status;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Schema(name = "status", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("status")
|
||||
public StatusEnum getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(StatusEnum status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public AttachmentDTO variants(List<@Valid VariantDTO> variants) {
|
||||
this.variants = variants;
|
||||
return this;
|
||||
}
|
||||
|
||||
public AttachmentDTO addVariantsItem(VariantDTO variantsItem) {
|
||||
if (this.variants == null) {
|
||||
this.variants = new ArrayList<>();
|
||||
}
|
||||
this.variants.add(variantsItem);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(name = "variants", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("variants")
|
||||
public List<@Valid VariantDTO> getVariants() {
|
||||
return variants;
|
||||
}
|
||||
|
||||
public void setVariants(List<@Valid VariantDTO> variants) {
|
||||
this.variants = variants;
|
||||
}
|
||||
|
||||
public AttachmentDTO errorCode(String errorCode) {
|
||||
this.errorCode = errorCode;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Schema(name = "error_code", requiredMode = Schema.RequiredMode.REQUIRED, nullable = true)
|
||||
@JsonProperty("error_code")
|
||||
public String getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
|
||||
public void setErrorCode(String errorCode) {
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public AttachmentDTO createdAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("created_at")
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public AttachmentDTO updatedAt(Instant updatedAt) {
|
||||
this.updatedAt = updatedAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Schema(name = "updated_at", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("updated_at")
|
||||
public Instant getUpdatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
|
||||
public void setUpdatedAt(Instant updatedAt) {
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
AttachmentDTO attachment = (AttachmentDTO) o;
|
||||
return Objects.equals(this.id, attachment.id)
|
||||
&& Objects.equals(this.chatId, attachment.chatId)
|
||||
&& Objects.equals(this.ownerId, attachment.ownerId)
|
||||
&& Objects.equals(this.filename, attachment.filename)
|
||||
&& Objects.equals(this.contentType, attachment.contentType)
|
||||
&& Objects.equals(this.sizeBytes, attachment.sizeBytes)
|
||||
&& Objects.equals(this.sha256, attachment.sha256)
|
||||
&& Objects.equals(this.status, attachment.status)
|
||||
&& Objects.equals(this.variants, attachment.variants)
|
||||
&& Objects.equals(this.errorCode, attachment.errorCode)
|
||||
&& Objects.equals(this.createdAt, attachment.createdAt)
|
||||
&& Objects.equals(this.updatedAt, attachment.updatedAt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(
|
||||
id,
|
||||
chatId,
|
||||
ownerId,
|
||||
filename,
|
||||
contentType,
|
||||
sizeBytes,
|
||||
sha256,
|
||||
status,
|
||||
variants,
|
||||
errorCode,
|
||||
createdAt,
|
||||
updatedAt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class AttachmentDTO {\n");
|
||||
sb.append(" id: ").append(toIndentedString(id)).append("\n");
|
||||
sb.append(" chatId: ").append(toIndentedString(chatId)).append("\n");
|
||||
sb.append(" ownerId: ").append(toIndentedString(ownerId)).append("\n");
|
||||
sb.append(" filename: ").append(toIndentedString(filename)).append("\n");
|
||||
sb.append(" contentType: ").append(toIndentedString(contentType)).append("\n");
|
||||
sb.append(" sizeBytes: ").append(toIndentedString(sizeBytes)).append("\n");
|
||||
sb.append(" sha256: ").append(toIndentedString(sha256)).append("\n");
|
||||
sb.append(" status: ").append(toIndentedString(status)).append("\n");
|
||||
sb.append(" variants: ").append(toIndentedString(variants)).append("\n");
|
||||
sb.append(" errorCode: ").append(toIndentedString(errorCode)).append("\n");
|
||||
sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n");
|
||||
sb.append(" updatedAt: ").append(toIndentedString(updatedAt)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String toIndentedString(Object o) {
|
||||
if (o == null) {
|
||||
return "null";
|
||||
}
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.annotation.Generated;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import org.hibernate.validator.constraints.CodePointLength;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
@Generated(
|
||||
value = "org.openapitools.codegen.languages.SpringCodegen",
|
||||
comments = "Generator version: 7.10.0")
|
||||
public class ChatDTO {
|
||||
|
||||
private UUID id;
|
||||
|
||||
private String title;
|
||||
|
||||
@Valid private List<UUID> memberIds = new ArrayList<>();
|
||||
|
||||
private Instant createdAt;
|
||||
|
||||
public ChatDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ChatDTO(String title, List<UUID> memberIds) {
|
||||
this.title = title;
|
||||
this.memberIds = memberIds;
|
||||
}
|
||||
|
||||
public ChatDTO id(UUID id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@Schema(name = "id", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("id")
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public ChatDTO title(String title) {
|
||||
this.title = title;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@CodePointLength(min = 1, max = 100)
|
||||
@Schema(name = "title", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("title")
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public ChatDTO memberIds(List<UUID> memberIds) {
|
||||
this.memberIds = memberIds;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ChatDTO addMemberIdsItem(UUID memberIdsItem) {
|
||||
if (this.memberIds == null) {
|
||||
this.memberIds = new ArrayList<>();
|
||||
}
|
||||
this.memberIds.add(memberIdsItem);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Size(min = 1, max = 100)
|
||||
@Schema(name = "member_ids", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("member_ids")
|
||||
public List<UUID> getMemberIds() {
|
||||
return memberIds;
|
||||
}
|
||||
|
||||
public void setMemberIds(List<UUID> memberIds) {
|
||||
this.memberIds = memberIds;
|
||||
}
|
||||
|
||||
public ChatDTO createdAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("created_at")
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
ChatDTO createChat = (ChatDTO) o;
|
||||
return Objects.equals(this.id, createChat.id)
|
||||
&& Objects.equals(this.title, createChat.title)
|
||||
&& Objects.equals(this.memberIds, createChat.memberIds)
|
||||
&& Objects.equals(this.createdAt, createChat.createdAt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, title, memberIds, createdAt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class ChatDTO {\n");
|
||||
sb.append(" id: ").append(toIndentedString(id)).append("\n");
|
||||
sb.append(" title: ").append(toIndentedString(title)).append("\n");
|
||||
sb.append(" memberIds: ").append(toIndentedString(memberIds)).append("\n");
|
||||
sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String toIndentedString(Object o) {
|
||||
if (o == null) {
|
||||
return "null";
|
||||
}
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public class ChatPageDTO {
|
||||
|
||||
@Valid private List<@Valid ChatDTO> items = new ArrayList<>();
|
||||
|
||||
private String nextCursor = null;
|
||||
|
||||
public ChatPageDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ChatPageDTO(List<@Valid ChatDTO> items, String nextCursor) {
|
||||
this.items = items;
|
||||
this.nextCursor = nextCursor;
|
||||
}
|
||||
|
||||
public ChatPageDTO items(List<@Valid ChatDTO> items) {
|
||||
this.items = items;
|
||||
return this;
|
||||
}
|
||||
|
||||
public ChatPageDTO addItemsItem(ChatDTO itemsItem) {
|
||||
if (this.items == null) {
|
||||
this.items = new ArrayList<>();
|
||||
}
|
||||
this.items.add(itemsItem);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(name = "items", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("items")
|
||||
public List<@Valid ChatDTO> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public void setItems(List<@Valid ChatDTO> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
public ChatPageDTO nextCursor(String nextCursor) {
|
||||
this.nextCursor = nextCursor;
|
||||
return this;
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.ALWAYS)
|
||||
@Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
|
||||
@JsonProperty("next_cursor")
|
||||
public String getNextCursor() {
|
||||
return nextCursor;
|
||||
}
|
||||
|
||||
public void setNextCursor(String nextCursor) {
|
||||
this.nextCursor = nextCursor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
ChatPageDTO chatPageDTO = (ChatPageDTO) o;
|
||||
return Objects.equals(this.items, chatPageDTO.items)
|
||||
&& Objects.equals(this.nextCursor, chatPageDTO.nextCursor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(items, nextCursor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class ChatPageDTO {\n");
|
||||
sb.append(" items: ").append(toIndentedString(items)).append("\n");
|
||||
sb.append(" nextCursor: ").append(toIndentedString(nextCursor)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String toIndentedString(Object o) {
|
||||
if (o == null) {
|
||||
return "null";
|
||||
}
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.annotation.Generated;
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import org.hibernate.validator.constraints.CodePointLength;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
@Generated(
|
||||
value = "org.openapitools.codegen.languages.SpringCodegen",
|
||||
comments = "Generator version: 7.10.0")
|
||||
public class CreateChatDTO {
|
||||
|
||||
private String title;
|
||||
|
||||
@Valid private List<UUID> memberIds = new ArrayList<>();
|
||||
|
||||
public CreateChatDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public CreateChatDTO(String title, List<UUID> memberIds) {
|
||||
this.title = title;
|
||||
this.memberIds = memberIds;
|
||||
}
|
||||
|
||||
public CreateChatDTO title(String title) {
|
||||
this.title = title;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@CodePointLength(min = 1, max = 100)
|
||||
@Schema(name = "title", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("title")
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public CreateChatDTO memberIds(List<UUID> memberIds) {
|
||||
this.memberIds = memberIds;
|
||||
return this;
|
||||
}
|
||||
|
||||
public CreateChatDTO addMemberIdsItem(UUID memberIdsItem) {
|
||||
if (this.memberIds == null) {
|
||||
this.memberIds = new ArrayList<>();
|
||||
}
|
||||
this.memberIds.add(memberIdsItem);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Size(min = 1, max = 100)
|
||||
@Schema(name = "member_ids", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("member_ids")
|
||||
public List<UUID> getMemberIds() {
|
||||
return memberIds;
|
||||
}
|
||||
|
||||
public void setMemberIds(List<UUID> memberIds) {
|
||||
this.memberIds = memberIds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
CreateChatDTO that = (CreateChatDTO) o;
|
||||
return Objects.equals(title, that.title) && Objects.equals(memberIds, that.memberIds);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(title, memberIds);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class CreateChatDTO {\n");
|
||||
sb.append(" title: ").append(toIndentedString(title)).append("\n");
|
||||
sb.append(" memberIds: ").append(toIndentedString(memberIds)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String toIndentedString(Object o) {
|
||||
if (o == null) return "null";
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
@Schema(name = "CreateMessage")
|
||||
public class CreateMessageDTO {
|
||||
|
||||
private String text;
|
||||
|
||||
private List<UUID> attachmentIds = new ArrayList<>();
|
||||
|
||||
public CreateMessageDTO() {}
|
||||
|
||||
public CreateMessageDTO text(String text) {
|
||||
this.text = text;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("text")
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
@Schema(name = "attachment_ids", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
|
||||
@JsonProperty("attachment_ids")
|
||||
public List<UUID> getAttachmentIds() {
|
||||
return attachmentIds;
|
||||
}
|
||||
|
||||
public void setAttachmentIds(List<UUID> attachmentIds) {
|
||||
this.attachmentIds = attachmentIds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof CreateMessageDTO d)) return false;
|
||||
return Objects.equals(text, d.text) && Objects.equals(attachmentIds, d.attachmentIds);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(text, attachmentIds);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.annotation.Generated;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
|
||||
import org.hibernate.validator.constraints.CodePointLength;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Generated(
|
||||
value = "org.openapitools.codegen.languages.SpringCodegen",
|
||||
comments = "Generator version: 7.10.0")
|
||||
public class CreateUserDTO {
|
||||
|
||||
private String username;
|
||||
|
||||
private String displayName;
|
||||
|
||||
private String password;
|
||||
|
||||
public CreateUserDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public CreateUserDTO(String username, String displayName, String password) {
|
||||
this.username = username;
|
||||
this.displayName = displayName;
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
public CreateUserDTO username(String username) {
|
||||
this.username = username;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Pattern(regexp = "^[a-z0-9_]{3,32}$")
|
||||
@Schema(name = "username", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("username")
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public CreateUserDTO displayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@CodePointLength(min = 1, max = 100)
|
||||
@Schema(name = "display_name", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("display_name")
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public void setDisplayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public CreateUserDTO password(String password) {
|
||||
this.password = password;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@CodePointLength(min = 12, max = 128)
|
||||
@Schema(
|
||||
name = "password",
|
||||
requiredMode = Schema.RequiredMode.REQUIRED,
|
||||
accessMode = Schema.AccessMode.WRITE_ONLY)
|
||||
@JsonProperty(value = "password", access = JsonProperty.Access.WRITE_ONLY)
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || getClass() != o.getClass()) return false;
|
||||
CreateUserDTO createUser = (CreateUserDTO) o;
|
||||
return Objects.equals(this.username, createUser.username)
|
||||
&& Objects.equals(this.displayName, createUser.displayName)
|
||||
&& Objects.equals(this.password, createUser.password);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(username, displayName, password);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class CreateUserDTO {\n");
|
||||
sb.append(" username: ").append(toIndentedString(username)).append("\n");
|
||||
sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n");
|
||||
sb.append(" password: ").append(password != null ? "***" : "null").append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String toIndentedString(Object o) {
|
||||
if (o == null) return "null";
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class ErrorDTO {
|
||||
|
||||
private ErrorErrorDTO error;
|
||||
|
||||
public ErrorDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ErrorDTO(ErrorErrorDTO error) {
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
public ErrorDTO error(ErrorErrorDTO error) {
|
||||
this.error = error;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(name = "error", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("error")
|
||||
public ErrorErrorDTO getError() {
|
||||
return error;
|
||||
}
|
||||
|
||||
public void setError(ErrorErrorDTO error) {
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
ErrorDTO errorDTO = (ErrorDTO) o;
|
||||
return Objects.equals(this.error, errorDTO.error);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(error);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class ErrorDTO {\n");
|
||||
sb.append(" error: ").append(toIndentedString(error)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String toIndentedString(Object o) {
|
||||
if (o == null) {
|
||||
return "null";
|
||||
}
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class ErrorErrorDTO {
|
||||
|
||||
public enum CodeEnum {
|
||||
INVALID_REQUEST("invalid_request"),
|
||||
UNAUTHORIZED("unauthorized"),
|
||||
NOT_FOUND("not_found"),
|
||||
CONFLICT("conflict"),
|
||||
PAYLOAD_TOO_LARGE("payload_too_large"),
|
||||
UNSUPPORTED_MEDIA_TYPE("unsupported_media_type"),
|
||||
RATE_LIMITED("rate_limited"),
|
||||
UNAVAILABLE("unavailable"),
|
||||
INTERNAL_ERROR("internal_error");
|
||||
|
||||
private String value;
|
||||
|
||||
CodeEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static CodeEnum fromValue(String value) {
|
||||
for (CodeEnum b : CodeEnum.values()) {
|
||||
if (b.value.equals(value)) {
|
||||
return b;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unexpected value '" + value + "'");
|
||||
}
|
||||
}
|
||||
|
||||
private CodeEnum code;
|
||||
|
||||
private String message;
|
||||
|
||||
private String requestId;
|
||||
|
||||
public ErrorErrorDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ErrorErrorDTO(CodeEnum code, String message, String requestId) {
|
||||
this.code = code;
|
||||
this.message = message;
|
||||
this.requestId = requestId;
|
||||
}
|
||||
|
||||
public ErrorErrorDTO code(CodeEnum code) {
|
||||
this.code = code;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Schema(name = "code", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("code")
|
||||
public CodeEnum getCode() {
|
||||
return code;
|
||||
}
|
||||
|
||||
public void setCode(CodeEnum code) {
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
public ErrorErrorDTO message(String message) {
|
||||
this.message = message;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Size(min = 1)
|
||||
@Schema(name = "message", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("message")
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public ErrorErrorDTO requestId(String requestId) {
|
||||
this.requestId = requestId;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Size(min = 1)
|
||||
@Schema(name = "request_id", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("request_id")
|
||||
public String getRequestId() {
|
||||
return requestId;
|
||||
}
|
||||
|
||||
public void setRequestId(String requestId) {
|
||||
this.requestId = requestId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
ErrorErrorDTO errorErrorDTO = (ErrorErrorDTO) o;
|
||||
return Objects.equals(this.code, errorErrorDTO.code)
|
||||
&& Objects.equals(this.message, errorErrorDTO.message)
|
||||
&& Objects.equals(this.requestId, errorErrorDTO.requestId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(code, message, requestId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class ErrorErrorDTO {\n");
|
||||
sb.append(" code: ").append(toIndentedString(code)).append("\n");
|
||||
sb.append(" message: ").append(toIndentedString(message)).append("\n");
|
||||
sb.append(" requestId: ").append(toIndentedString(requestId)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String toIndentedString(Object o) {
|
||||
if (o == null) {
|
||||
return "null";
|
||||
}
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
public class HealthDTO {
|
||||
|
||||
public enum StatusEnum {
|
||||
OK("ok");
|
||||
|
||||
private String value;
|
||||
|
||||
StatusEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static StatusEnum fromValue(String value) {
|
||||
for (StatusEnum b : StatusEnum.values()) {
|
||||
if (b.value.equals(value)) {
|
||||
return b;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unexpected value '" + value + "'");
|
||||
}
|
||||
}
|
||||
|
||||
private StatusEnum status;
|
||||
|
||||
public HealthDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public HealthDTO(StatusEnum status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public HealthDTO status(StatusEnum status) {
|
||||
this.status = status;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Schema(name = "status", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("status")
|
||||
public StatusEnum getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(StatusEnum status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
HealthDTO healthDTO = (HealthDTO) o;
|
||||
return Objects.equals(this.status, healthDTO.status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class HealthDTO {\n");
|
||||
sb.append(" status: ").append(toIndentedString(status)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String toIndentedString(Object o) {
|
||||
if (o == null) {
|
||||
return "null";
|
||||
}
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import org.hibernate.validator.constraints.CodePointLength;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public class MessageDTO {
|
||||
|
||||
private UUID id;
|
||||
|
||||
private UUID chatId;
|
||||
|
||||
private UUID senderId;
|
||||
|
||||
private String text;
|
||||
|
||||
private Instant createdAt;
|
||||
|
||||
private List<UUID> attachmentIds = new ArrayList<>();
|
||||
|
||||
public MessageDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MessageDTO(UUID id, UUID chatId, UUID senderId, String text, Instant createdAt) {
|
||||
this.id = id;
|
||||
this.chatId = chatId;
|
||||
this.senderId = senderId;
|
||||
this.text = text;
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public MessageDTO(
|
||||
UUID id,
|
||||
UUID chatId,
|
||||
UUID senderId,
|
||||
String text,
|
||||
Instant createdAt,
|
||||
List<UUID> attachmentIds) {
|
||||
this.id = id;
|
||||
this.chatId = chatId;
|
||||
this.senderId = senderId;
|
||||
this.text = text;
|
||||
this.createdAt = createdAt;
|
||||
this.attachmentIds = attachmentIds != null ? attachmentIds : new ArrayList<>();
|
||||
}
|
||||
|
||||
public MessageDTO id(UUID id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(name = "id", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("id")
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public MessageDTO chatId(UUID chatId) {
|
||||
this.chatId = chatId;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(name = "chat_id", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("chat_id")
|
||||
public UUID getChatId() {
|
||||
return chatId;
|
||||
}
|
||||
|
||||
public void setChatId(UUID chatId) {
|
||||
this.chatId = chatId;
|
||||
}
|
||||
|
||||
public MessageDTO senderId(UUID senderId) {
|
||||
this.senderId = senderId;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(name = "sender_id", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("sender_id")
|
||||
public UUID getSenderId() {
|
||||
return senderId;
|
||||
}
|
||||
|
||||
public void setSenderId(UUID senderId) {
|
||||
this.senderId = senderId;
|
||||
}
|
||||
|
||||
public MessageDTO text(String text) {
|
||||
this.text = text;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@CodePointLength(min = 1, max = 4000)
|
||||
@Schema(name = "text", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("text")
|
||||
public String getText() {
|
||||
return text;
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
this.text = text;
|
||||
}
|
||||
|
||||
public MessageDTO createdAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("created_at")
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@Schema(name = "attachment_ids", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("attachment_ids")
|
||||
public List<UUID> getAttachmentIds() {
|
||||
return attachmentIds;
|
||||
}
|
||||
|
||||
public void setAttachmentIds(List<UUID> attachmentIds) {
|
||||
this.attachmentIds = attachmentIds;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
MessageDTO messageDTO = (MessageDTO) o;
|
||||
return Objects.equals(this.id, messageDTO.id)
|
||||
&& Objects.equals(this.chatId, messageDTO.chatId)
|
||||
&& Objects.equals(this.senderId, messageDTO.senderId)
|
||||
&& Objects.equals(this.text, messageDTO.text)
|
||||
&& Objects.equals(this.createdAt, messageDTO.createdAt)
|
||||
&& Objects.equals(this.attachmentIds, messageDTO.attachmentIds);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, chatId, senderId, text, createdAt, attachmentIds);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class MessageDTO {\n");
|
||||
sb.append(" id: ").append(toIndentedString(id)).append("\n");
|
||||
sb.append(" chatId: ").append(toIndentedString(chatId)).append("\n");
|
||||
sb.append(" senderId: ").append(toIndentedString(senderId)).append("\n");
|
||||
sb.append(" text: ").append(toIndentedString(text)).append("\n");
|
||||
sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n");
|
||||
sb.append(" attachmentIds: ").append(toIndentedString(attachmentIds)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String toIndentedString(Object o) {
|
||||
if (o == null) {
|
||||
return "null";
|
||||
}
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public class MessagePageDTO {
|
||||
|
||||
@Valid private List<@Valid MessageDTO> items = new ArrayList<>();
|
||||
|
||||
private String nextCursor = null;
|
||||
|
||||
public MessagePageDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public MessagePageDTO(List<@Valid MessageDTO> items, String nextCursor) {
|
||||
this.items = items;
|
||||
this.nextCursor = nextCursor;
|
||||
}
|
||||
|
||||
public MessagePageDTO items(List<@Valid MessageDTO> items) {
|
||||
this.items = items;
|
||||
return this;
|
||||
}
|
||||
|
||||
public MessagePageDTO addItemsItem(MessageDTO itemsItem) {
|
||||
if (this.items == null) {
|
||||
this.items = new ArrayList<>();
|
||||
}
|
||||
this.items.add(itemsItem);
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(name = "items", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("items")
|
||||
public List<@Valid MessageDTO> getItems() {
|
||||
return items;
|
||||
}
|
||||
|
||||
public void setItems(List<@Valid MessageDTO> items) {
|
||||
this.items = items;
|
||||
}
|
||||
|
||||
public MessagePageDTO nextCursor(String nextCursor) {
|
||||
this.nextCursor = nextCursor;
|
||||
return this;
|
||||
}
|
||||
|
||||
@JsonInclude(JsonInclude.Include.ALWAYS)
|
||||
@Schema(name = "next_cursor", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
|
||||
@JsonProperty("next_cursor")
|
||||
public String getNextCursor() {
|
||||
return nextCursor;
|
||||
}
|
||||
|
||||
public void setNextCursor(String nextCursor) {
|
||||
this.nextCursor = nextCursor;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
MessagePageDTO messagePageDTO = (MessagePageDTO) o;
|
||||
return Objects.equals(this.items, messagePageDTO.items)
|
||||
&& Objects.equals(this.nextCursor, messagePageDTO.nextCursor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(items, nextCursor);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class MessagePageDTO {\n");
|
||||
sb.append(" items: ").append(toIndentedString(items)).append("\n");
|
||||
sb.append(" nextCursor: ").append(toIndentedString(nextCursor)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String toIndentedString(Object o) {
|
||||
if (o == null) {
|
||||
return "null";
|
||||
}
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
public class SessionDTO {
|
||||
|
||||
private String token;
|
||||
|
||||
public enum TokenTypeEnum {
|
||||
BEARER("Bearer");
|
||||
|
||||
private String value;
|
||||
|
||||
TokenTypeEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static TokenTypeEnum fromValue(String value) {
|
||||
for (TokenTypeEnum b : TokenTypeEnum.values()) {
|
||||
if (b.value.equals(value)) {
|
||||
return b;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unexpected value '" + value + "'");
|
||||
}
|
||||
}
|
||||
|
||||
private TokenTypeEnum tokenType;
|
||||
|
||||
private Instant expiresAt;
|
||||
|
||||
private UserDTO user;
|
||||
|
||||
public SessionDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public SessionDTO(String token, TokenTypeEnum tokenType, Instant expiresAt, UserDTO user) {
|
||||
this.token = token;
|
||||
this.tokenType = tokenType;
|
||||
this.expiresAt = expiresAt;
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public SessionDTO token(String token) {
|
||||
this.token = token;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Size(min = 32)
|
||||
@Schema(name = "token", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("token")
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public void setToken(String token) {
|
||||
this.token = token;
|
||||
}
|
||||
|
||||
public SessionDTO tokenType(TokenTypeEnum tokenType) {
|
||||
this.tokenType = tokenType;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Schema(name = "token_type", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("token_type")
|
||||
public TokenTypeEnum getTokenType() {
|
||||
return tokenType;
|
||||
}
|
||||
|
||||
public void setTokenType(TokenTypeEnum tokenType) {
|
||||
this.tokenType = tokenType;
|
||||
}
|
||||
|
||||
public SessionDTO expiresAt(Instant expiresAt) {
|
||||
this.expiresAt = expiresAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(name = "expires_at", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("expires_at")
|
||||
public Instant getExpiresAt() {
|
||||
return expiresAt;
|
||||
}
|
||||
|
||||
public void setExpiresAt(Instant expiresAt) {
|
||||
this.expiresAt = expiresAt;
|
||||
}
|
||||
|
||||
public SessionDTO user(UserDTO user) {
|
||||
this.user = user;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Valid
|
||||
@Schema(name = "user", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("user")
|
||||
public UserDTO getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(UserDTO user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
SessionDTO sessionDTO = (SessionDTO) o;
|
||||
return Objects.equals(this.token, sessionDTO.token)
|
||||
&& Objects.equals(this.tokenType, sessionDTO.tokenType)
|
||||
&& Objects.equals(this.expiresAt, sessionDTO.expiresAt)
|
||||
&& Objects.equals(this.user, sessionDTO.user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(token, tokenType, expiresAt, user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class SessionDTO {\n");
|
||||
sb.append(" token: ").append(toIndentedString(token)).append("\n");
|
||||
sb.append(" tokenType: ").append(toIndentedString(tokenType)).append("\n");
|
||||
sb.append(" expiresAt: ").append(toIndentedString(expiresAt)).append("\n");
|
||||
sb.append(" user: ").append(toIndentedString(user)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String toIndentedString(Object o) {
|
||||
if (o == null) {
|
||||
return "null";
|
||||
}
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
|
||||
import org.hibernate.validator.constraints.CodePointLength;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
public class UserDTO {
|
||||
|
||||
private UUID id;
|
||||
|
||||
private String username;
|
||||
|
||||
private String displayName;
|
||||
|
||||
private Instant createdAt;
|
||||
|
||||
public UserDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public UserDTO(String username, String displayName) {
|
||||
this.username = username;
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public UserDTO username(String username) {
|
||||
this.username = username;
|
||||
return this;
|
||||
}
|
||||
|
||||
@Valid
|
||||
@Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED)
|
||||
@JsonProperty("id")
|
||||
public UUID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(UUID id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public UserDTO id(UUID id) {
|
||||
this.id = id;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Pattern(regexp = "^[a-z0-9_]{3,32}$")
|
||||
@Schema(name = "username", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("username")
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public UserDTO displayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@CodePointLength(min = 1, max = 100)
|
||||
@Schema(name = "display_name", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("display_name")
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public void setDisplayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public UserDTO createdAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Schema(name = "created_at", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("created_at")
|
||||
public Instant getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(Instant createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
UserDTO userDTO = (UserDTO) o;
|
||||
return Objects.equals(this.id, userDTO.id)
|
||||
&& Objects.equals(this.username, userDTO.username)
|
||||
&& Objects.equals(this.displayName, userDTO.displayName)
|
||||
&& Objects.equals(this.createdAt, userDTO.createdAt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(id, username, displayName, createdAt);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class UserDTO {\n");
|
||||
sb.append(" id: ").append(toIndentedString(id)).append("\n");
|
||||
sb.append(" username: ").append(toIndentedString(username)).append("\n");
|
||||
sb.append(" displayName: ").append(toIndentedString(displayName)).append("\n");
|
||||
sb.append(" createdAt: ").append(toIndentedString(createdAt)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String toIndentedString(Object o) {
|
||||
if (o == null) {
|
||||
return "null";
|
||||
}
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
package ru.mtusi.messenger.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonCreator;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import com.fasterxml.jackson.annotation.JsonValue;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import jakarta.annotation.Generated;
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Pattern;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Generated(
|
||||
value = "org.openapitools.codegen.languages.SpringCodegen",
|
||||
comments = "Generator version: 7.10.0")
|
||||
public class VariantDTO {
|
||||
|
||||
public enum NameEnum {
|
||||
THUMBNAIL("thumbnail"),
|
||||
CROP("crop"),
|
||||
OPTIMIZED("optimized");
|
||||
|
||||
private final String value;
|
||||
|
||||
NameEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static NameEnum fromValue(String value) {
|
||||
for (NameEnum b : NameEnum.values()) {
|
||||
if (b.value.equals(value)) {
|
||||
return b;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unexpected value '" + value + "'");
|
||||
}
|
||||
}
|
||||
|
||||
private NameEnum name;
|
||||
|
||||
public enum ContentTypeEnum {
|
||||
IMAGE_JPEG("image/jpeg"),
|
||||
IMAGE_PNG("image/png"),
|
||||
IMAGE_WEBP("image/webp");
|
||||
|
||||
private final String value;
|
||||
|
||||
ContentTypeEnum(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
@JsonValue
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return String.valueOf(value);
|
||||
}
|
||||
|
||||
@JsonCreator
|
||||
public static ContentTypeEnum fromValue(String value) {
|
||||
for (ContentTypeEnum b : ContentTypeEnum.values()) {
|
||||
if (b.value.equals(value)) {
|
||||
return b;
|
||||
}
|
||||
}
|
||||
throw new IllegalArgumentException("Unexpected value '" + value + "'");
|
||||
}
|
||||
}
|
||||
|
||||
private ContentTypeEnum contentType;
|
||||
|
||||
private Long sizeBytes;
|
||||
|
||||
private Integer width;
|
||||
|
||||
private Integer height;
|
||||
|
||||
private String sha256;
|
||||
|
||||
public VariantDTO() {
|
||||
super();
|
||||
}
|
||||
|
||||
public VariantDTO(
|
||||
NameEnum name,
|
||||
ContentTypeEnum contentType,
|
||||
Long sizeBytes,
|
||||
Integer width,
|
||||
Integer height,
|
||||
String sha256) {
|
||||
this.name = name;
|
||||
this.contentType = contentType;
|
||||
this.sizeBytes = sizeBytes;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
this.sha256 = sha256;
|
||||
}
|
||||
|
||||
public VariantDTO name(NameEnum name) {
|
||||
this.name = name;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Schema(name = "name", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("name")
|
||||
public NameEnum getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(NameEnum name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public VariantDTO contentType(ContentTypeEnum contentType) {
|
||||
this.contentType = contentType;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Schema(name = "content_type", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("content_type")
|
||||
public ContentTypeEnum getContentType() {
|
||||
return contentType;
|
||||
}
|
||||
|
||||
public void setContentType(ContentTypeEnum contentType) {
|
||||
this.contentType = contentType;
|
||||
}
|
||||
|
||||
public VariantDTO sizeBytes(Long sizeBytes) {
|
||||
this.sizeBytes = sizeBytes;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Min(1L)
|
||||
@Schema(name = "size_bytes", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("size_bytes")
|
||||
public Long getSizeBytes() {
|
||||
return sizeBytes;
|
||||
}
|
||||
|
||||
public void setSizeBytes(Long sizeBytes) {
|
||||
this.sizeBytes = sizeBytes;
|
||||
}
|
||||
|
||||
public VariantDTO width(Integer width) {
|
||||
this.width = width;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
@Schema(name = "width", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("width")
|
||||
public Integer getWidth() {
|
||||
return width;
|
||||
}
|
||||
|
||||
public void setWidth(Integer width) {
|
||||
this.width = width;
|
||||
}
|
||||
|
||||
public VariantDTO height(Integer height) {
|
||||
this.height = height;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Min(1)
|
||||
@Schema(name = "height", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("height")
|
||||
public Integer getHeight() {
|
||||
return height;
|
||||
}
|
||||
|
||||
public void setHeight(Integer height) {
|
||||
this.height = height;
|
||||
}
|
||||
|
||||
public VariantDTO sha256(String sha256) {
|
||||
this.sha256 = sha256;
|
||||
return this;
|
||||
}
|
||||
|
||||
@NotNull
|
||||
@Pattern(regexp = "^[a-f0-9]{64}$")
|
||||
@Schema(name = "sha256", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
@JsonProperty("sha256")
|
||||
public String getSha256() {
|
||||
return sha256;
|
||||
}
|
||||
|
||||
public void setSha256(String sha256) {
|
||||
this.sha256 = sha256;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) {
|
||||
return true;
|
||||
}
|
||||
if (o == null || getClass() != o.getClass()) {
|
||||
return false;
|
||||
}
|
||||
VariantDTO variant = (VariantDTO) o;
|
||||
return Objects.equals(this.name, variant.name)
|
||||
&& Objects.equals(this.contentType, variant.contentType)
|
||||
&& Objects.equals(this.sizeBytes, variant.sizeBytes)
|
||||
&& Objects.equals(this.width, variant.width)
|
||||
&& Objects.equals(this.height, variant.height)
|
||||
&& Objects.equals(this.sha256, variant.sha256);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(name, contentType, sizeBytes, width, height, sha256);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("class VariantDTO {\n");
|
||||
sb.append(" name: ").append(toIndentedString(name)).append("\n");
|
||||
sb.append(" contentType: ").append(toIndentedString(contentType)).append("\n");
|
||||
sb.append(" sizeBytes: ").append(toIndentedString(sizeBytes)).append("\n");
|
||||
sb.append(" width: ").append(toIndentedString(width)).append("\n");
|
||||
sb.append(" height: ").append(toIndentedString(height)).append("\n");
|
||||
sb.append(" sha256: ").append(toIndentedString(sha256)).append("\n");
|
||||
sb.append("}");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String toIndentedString(Object o) {
|
||||
if (o == null) {
|
||||
return "null";
|
||||
}
|
||||
return o.toString().replace("\n", "\n ");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import ru.mtusi.messenger.dto.ErrorDTO;
|
||||
import ru.mtusi.messenger.dto.ErrorErrorDTO;
|
||||
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ApiErrorFactory {
|
||||
private static final String DEFAULT_MESSAGE = "Error";
|
||||
private static final String REQUEST_ID_ATTR = "requestId";
|
||||
private static final String REQUEST_ID_MDC = "requestId";
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public ErrorDTO error(ErrorErrorDTO.CodeEnum code, String message, HttpServletRequest request) {
|
||||
ErrorErrorDTO inner = new ErrorErrorDTO();
|
||||
inner.setCode(code);
|
||||
inner.setMessage(normalizeMessage(message));
|
||||
inner.setRequestId(resolveRequestId(request));
|
||||
|
||||
ErrorDTO outer = new ErrorDTO();
|
||||
outer.setError(inner);
|
||||
return outer;
|
||||
}
|
||||
|
||||
public void writeError(
|
||||
HttpServletResponse response,
|
||||
HttpServletRequest request,
|
||||
HttpStatus status,
|
||||
String wwwAuthenticate,
|
||||
ErrorErrorDTO.CodeEnum code,
|
||||
String message)
|
||||
throws IOException {
|
||||
String requestId = resolveRequestId(request);
|
||||
response.setStatus(status.value());
|
||||
response.setHeader("X-Request-Id", requestId);
|
||||
if (wwwAuthenticate != null) {
|
||||
response.setHeader(HttpHeaders.WWW_AUTHENTICATE, wwwAuthenticate);
|
||||
}
|
||||
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
|
||||
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
|
||||
objectMapper.writeValue(response.getWriter(), error(code, message, request));
|
||||
}
|
||||
|
||||
public String resolveRequestId(HttpServletRequest request) {
|
||||
Object attr = request.getAttribute(REQUEST_ID_ATTR);
|
||||
if (attr instanceof String s && !s.isBlank()) {
|
||||
return s;
|
||||
}
|
||||
String mdc = MDC.get(REQUEST_ID_MDC);
|
||||
if (mdc != null && !mdc.isBlank()) {
|
||||
request.setAttribute(REQUEST_ID_ATTR, mdc);
|
||||
return mdc;
|
||||
}
|
||||
String generated = UUID.randomUUID().toString();
|
||||
request.setAttribute(REQUEST_ID_ATTR, generated);
|
||||
return generated;
|
||||
}
|
||||
|
||||
private String normalizeMessage(String message) {
|
||||
return (message == null || message.isBlank()) ? DEFAULT_MESSAGE : message;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class ConflictException extends RuntimeException {
|
||||
public ConflictException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class InvalidRequestException extends RuntimeException {
|
||||
public InvalidRequestException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class NotFoundException extends RuntimeException {
|
||||
public NotFoundException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class PayloadTooLargeException extends RuntimeException {
|
||||
public PayloadTooLargeException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class RateLimitedException extends RuntimeException {
|
||||
public RateLimitedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class ServiceUnavailableException extends RuntimeException {
|
||||
public ServiceUnavailableException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class StaleAttachmentException extends RuntimeException {
|
||||
public StaleAttachmentException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
public StaleAttachmentException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class StorageUnavailableException extends RuntimeException {
|
||||
public StorageUnavailableException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class UnauthorizedException extends RuntimeException {
|
||||
public UnauthorizedException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.mtusi.messenger.exception;
|
||||
|
||||
public class UnsupportedMediaTypeException extends RuntimeException {
|
||||
public UnsupportedMediaTypeException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package ru.mtusi.messenger.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import ru.mtusi.messenger.config.properties.InstanceProperties;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE)
|
||||
@RequiredArgsConstructor
|
||||
public class InstanceIdFilter extends OncePerRequestFilter {
|
||||
|
||||
private final InstanceProperties props;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
response.setHeader("X-Instance-Id", props.id());
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package ru.mtusi.messenger.filter;
|
||||
|
||||
import io.github.bucket4j.Bucket;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import ru.mtusi.messenger.config.properties.RateLimitProperties;
|
||||
import ru.mtusi.messenger.dto.ErrorErrorDTO;
|
||||
import ru.mtusi.messenger.exception.ApiErrorFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
@Order(2)
|
||||
@RequiredArgsConstructor
|
||||
public class RateLimitFilter extends OncePerRequestFilter {
|
||||
private final RateLimitProperties limitProperties;
|
||||
private final Bucket bucket;
|
||||
private final ApiErrorFactory errors;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest req, HttpServletResponse res, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
if (!req.getRequestURI().startsWith("/api/")) {
|
||||
chain.doFilter(req, res);
|
||||
return;
|
||||
}
|
||||
|
||||
if (bucket.tryConsume(1)) {
|
||||
chain.doFilter(req, res);
|
||||
return;
|
||||
}
|
||||
|
||||
res.setHeader("Retry-After", String.valueOf(limitProperties.retryAfterSeconds()));
|
||||
errors.writeError(
|
||||
res,
|
||||
req,
|
||||
HttpStatus.TOO_MANY_REQUESTS,
|
||||
null,
|
||||
ErrorErrorDTO.CodeEnum.RATE_LIMITED,
|
||||
"Rate limit exceeded. Try again later.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package ru.mtusi.messenger.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
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.util.UUID;
|
||||
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
|
||||
public class RequestIdFilter extends OncePerRequestFilter {
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest req, HttpServletResponse res, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
String rid = UUID.randomUUID().toString();
|
||||
res.setHeader("X-Request-Id", rid);
|
||||
req.setAttribute("requestId", rid);
|
||||
MDC.put("requestId", rid);
|
||||
try {
|
||||
chain.doFilter(req, res);
|
||||
} finally {
|
||||
MDC.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package ru.mtusi.messenger.filter;
|
||||
|
||||
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.trace.Span;
|
||||
import io.opentelemetry.api.trace.StatusCode;
|
||||
|
||||
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 org.springframework.web.servlet.HandlerMapping;
|
||||
|
||||
import ru.mtusi.messenger.telemetry.Telemetry;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Component
|
||||
@Order(Ordered.HIGHEST_PRECEDENCE + 3)
|
||||
public class TelemetryFilter extends OncePerRequestFilter {
|
||||
private static final Set<String> METHODS =
|
||||
Set.of("GET", "POST", "DELETE", "PUT", "PATCH", "HEAD", "OPTIONS");
|
||||
private static final Set<String> ROUTES =
|
||||
Set.of(
|
||||
"/api/v1/users",
|
||||
"/api/v1/users/me",
|
||||
"/api/v1/auth/sessions",
|
||||
"/api/v1/auth/sessions/current",
|
||||
"/api/v1/chats",
|
||||
"/api/v1/chats/{chat_id}",
|
||||
"/api/v1/chats/{chat_id}/messages",
|
||||
"/api/v1/chats/{chat_id}/attachments",
|
||||
"/api/v1/attachments/{attachment_id}",
|
||||
"/api/v1/attachments/{attachment_id}/content");
|
||||
|
||||
private final Telemetry telemetry;
|
||||
private final LongCounter requests;
|
||||
private final DoubleHistogram duration;
|
||||
|
||||
public TelemetryFilter(Telemetry telemetry) {
|
||||
this.telemetry = telemetry;
|
||||
var meter = telemetry.openTelemetry().getMeter("ru.mtusi.messenger");
|
||||
requests = meter.counterBuilder("lab_http_requests").build();
|
||||
duration =
|
||||
meter.histogramBuilder("lab_http_duration")
|
||||
.setUnit("s")
|
||||
.setExplicitBucketBoundariesAdvice(
|
||||
List.of(
|
||||
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.0, 5.0,
|
||||
10.0, 30.0))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
return !request.getRequestURI().startsWith("/api/v1/");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
long started = System.nanoTime();
|
||||
Span span = telemetry.server(request);
|
||||
try (var scope = span.makeCurrent()) {
|
||||
int status = 500;
|
||||
try {
|
||||
chain.doFilter(request, response);
|
||||
status = response.getStatus();
|
||||
} finally {
|
||||
record(request, response, span, status, (System.nanoTime() - started) / 1e9);
|
||||
}
|
||||
} finally {
|
||||
span.end();
|
||||
}
|
||||
}
|
||||
|
||||
private void record(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
Span span,
|
||||
int status,
|
||||
double seconds) {
|
||||
String method = METHODS.contains(request.getMethod()) ? request.getMethod() : "OTHER";
|
||||
String pattern =
|
||||
String.valueOf(
|
||||
request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE));
|
||||
String route = ROUTES.contains(pattern) ? pattern : "unmatched";
|
||||
Attributes labels =
|
||||
Attributes.builder()
|
||||
.put("method", method)
|
||||
.put("route", route)
|
||||
.put("status_class", status / 100 + "xx")
|
||||
.build();
|
||||
requests.add(1, labels);
|
||||
duration.record(seconds, labels);
|
||||
span.updateName(method + " " + route);
|
||||
span.setAllAttributes(labels);
|
||||
span.setAttribute("http.response.status_code", status);
|
||||
if (status >= 500) {
|
||||
span.setStatus(StatusCode.ERROR);
|
||||
}
|
||||
String id = response.getHeader("X-Request-Id");
|
||||
Attributes log =
|
||||
labels.toBuilder()
|
||||
.put("event", "http.completed")
|
||||
.put("http.response.status_code", status)
|
||||
.put("duration_seconds", seconds)
|
||||
.put(AttributeKey.stringKey("request_id"), id == null ? "" : id)
|
||||
.build();
|
||||
telemetry.log("http.completed", status >= 500, log);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package ru.mtusi.messenger.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.Named;
|
||||
|
||||
import ru.mtusi.messenger.dto.AttachmentDTO;
|
||||
import ru.mtusi.messenger.model.Attachment;
|
||||
import ru.mtusi.messenger.model.AttachmentStatus;
|
||||
import ru.mtusi.messenger.model.Chat;
|
||||
import ru.mtusi.messenger.model.User;
|
||||
|
||||
import java.util.Collections;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface AttachmentMapper {
|
||||
@Mapping(target = "chatId", source = "chat.id")
|
||||
@Mapping(target = "ownerId", source = "owner.id")
|
||||
@Mapping(target = "sha256", source = "checksum")
|
||||
@Mapping(target = "status", source = "status", qualifiedByName = "mapStatus")
|
||||
@Mapping(target = "contentType", source = "contentType", qualifiedByName = "mapContentType")
|
||||
@Mapping(target = "variants", expression = "java(emptyVariants())")
|
||||
@Mapping(target = "errorCode", source = "errorCode")
|
||||
AttachmentDTO toDto(Attachment entity);
|
||||
|
||||
@Named("mapStatus")
|
||||
default AttachmentDTO.StatusEnum mapStatus(AttachmentStatus status) {
|
||||
return switch (status) {
|
||||
case QUEUED -> AttachmentDTO.StatusEnum.QUEUED;
|
||||
case PROCESSING -> AttachmentDTO.StatusEnum.PROCESSING;
|
||||
case READY -> AttachmentDTO.StatusEnum.READY;
|
||||
default -> AttachmentDTO.StatusEnum.FAILED;
|
||||
};
|
||||
}
|
||||
|
||||
@Named("mapContentType")
|
||||
default AttachmentDTO.ContentTypeEnum mapContentType(String contentType) {
|
||||
if (contentType == null) {
|
||||
return null;
|
||||
}
|
||||
return AttachmentDTO.ContentTypeEnum.fromValue(contentType);
|
||||
}
|
||||
|
||||
default java.util.List<ru.mtusi.messenger.dto.VariantDTO> emptyVariants() {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Mapping(target = "id", ignore = true)
|
||||
@Mapping(target = "createdAt", ignore = true)
|
||||
@Mapping(target = "updatedAt", ignore = true)
|
||||
@Mapping(target = "status", constant = "QUEUED")
|
||||
@Mapping(target = "objectKey", source = "objectKey")
|
||||
@Mapping(target = "stagingKey", source = "objectKey")
|
||||
@Mapping(target = "errorCode", ignore = true)
|
||||
@Mapping(target = "pipelineVersion", constant = "1L")
|
||||
Attachment toEntity(
|
||||
String objectKey,
|
||||
String filename,
|
||||
String contentType,
|
||||
Long sizeBytes,
|
||||
String checksum,
|
||||
Chat chat,
|
||||
User owner);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package ru.mtusi.messenger.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
import org.mapstruct.Named;
|
||||
|
||||
import ru.mtusi.messenger.dto.ChatDTO;
|
||||
import ru.mtusi.messenger.dto.CreateChatDTO;
|
||||
import ru.mtusi.messenger.model.Chat;
|
||||
import ru.mtusi.messenger.model.User;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface ChatMapper {
|
||||
|
||||
@Mapping(target = "id", ignore = true)
|
||||
@Mapping(target = "createdAt", ignore = true)
|
||||
@Mapping(target = "members", ignore = true)
|
||||
@Mapping(target = "messages", ignore = true)
|
||||
Chat toChat(CreateChatDTO dto);
|
||||
|
||||
@Mapping(target = "memberIds", source = "members", qualifiedByName = "usersToIds")
|
||||
ChatDTO toChatDto(Chat chat);
|
||||
|
||||
@Named("usersToIds")
|
||||
default List<UUID> usersToIds(Set<User> users) {
|
||||
if (users == null) return new ArrayList<>();
|
||||
List<UUID> ids = new ArrayList<>(users.size());
|
||||
for (User u : users) ids.add(u.getId());
|
||||
return ids;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package ru.mtusi.messenger.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
import ru.mtusi.messenger.dto.CreateMessageDTO;
|
||||
import ru.mtusi.messenger.dto.MessageDTO;
|
||||
import ru.mtusi.messenger.model.Message;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface MessageMapper {
|
||||
|
||||
@Mapping(target = "id", ignore = true)
|
||||
@Mapping(target = "chat", ignore = true)
|
||||
@Mapping(target = "sender", ignore = true)
|
||||
@Mapping(target = "createdAt", ignore = true)
|
||||
@Mapping(target = "attachmentIds", ignore = true)
|
||||
Message toMessage(MessageDTO dto);
|
||||
|
||||
@Mapping(target = "chatId", source = "chat.id")
|
||||
@Mapping(target = "senderId", source = "sender.id")
|
||||
@Mapping(target = "attachmentIds", source = "attachmentIds")
|
||||
MessageDTO toMessageDTO(Message entity);
|
||||
|
||||
@Mapping(target = "id", ignore = true)
|
||||
@Mapping(target = "chat", ignore = true)
|
||||
@Mapping(target = "sender", ignore = true)
|
||||
@Mapping(target = "createdAt", ignore = true)
|
||||
@Mapping(target = "attachmentIds", source = "attachmentIds")
|
||||
Message toMessage(CreateMessageDTO dto);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package ru.mtusi.messenger.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
import ru.mtusi.messenger.dto.SessionDTO;
|
||||
import ru.mtusi.messenger.dto.UserDTO;
|
||||
import ru.mtusi.messenger.model.Session;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface SessionMapper {
|
||||
|
||||
@Mapping(target = "token", source = "tokenRaw")
|
||||
@Mapping(
|
||||
target = "tokenType",
|
||||
expression = "java(ru.mtusi.messenger.dto.SessionDTO.TokenTypeEnum.BEARER)")
|
||||
@Mapping(target = "expiresAt", source = "session.expiresAt")
|
||||
@Mapping(target = "user", source = "userDTO")
|
||||
SessionDTO toSessionDTO(Session session, String tokenRaw, UserDTO userDTO);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package ru.mtusi.messenger.mapper;
|
||||
|
||||
import org.mapstruct.Mapper;
|
||||
import org.mapstruct.Mapping;
|
||||
|
||||
import ru.mtusi.messenger.dto.CreateUserDTO;
|
||||
import ru.mtusi.messenger.dto.UserDTO;
|
||||
import ru.mtusi.messenger.model.User;
|
||||
|
||||
@Mapper(componentModel = "spring")
|
||||
public interface UserMapper {
|
||||
|
||||
@Mapping(target = "id", ignore = true)
|
||||
@Mapping(target = "createdAt", ignore = true)
|
||||
@Mapping(target = "passwordHash", ignore = true)
|
||||
@Mapping(target = "chats", ignore = true)
|
||||
@Mapping(target = "messages", ignore = true)
|
||||
User toUser(CreateUserDTO dto);
|
||||
|
||||
UserDTO toUserDto(User user);
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package ru.mtusi.messenger.model;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.PreUpdate;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "attachments")
|
||||
@Getter
|
||||
@Setter
|
||||
public class Attachment {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@Column(name = "object_key", nullable = false, unique = true, length = 512)
|
||||
private String objectKey;
|
||||
|
||||
@Column(nullable = false, length = 255)
|
||||
private String filename;
|
||||
|
||||
@Column(name = "content_type", nullable = false, length = 100)
|
||||
private String contentType;
|
||||
|
||||
@Column(name = "size_bytes", nullable = false)
|
||||
private Long sizeBytes;
|
||||
|
||||
@Column(nullable = false, length = 64)
|
||||
private String checksum;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 20)
|
||||
private AttachmentStatus status;
|
||||
|
||||
@Column(name = "staging_key", length = 512)
|
||||
private String stagingKey;
|
||||
|
||||
@Column(name = "error_code", length = 64)
|
||||
private String errorCode;
|
||||
|
||||
@Column(name = "pipeline_version", nullable = false)
|
||||
private long pipelineVersion = 1;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "chat_id", nullable = false)
|
||||
private Chat chat;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "owner_id", nullable = false)
|
||||
private User owner;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "updated_at", nullable = false)
|
||||
private Instant updatedAt;
|
||||
|
||||
@PrePersist
|
||||
private void onCreate() {
|
||||
Instant now = Instant.now().truncatedTo(ChronoUnit.MILLIS);
|
||||
this.createdAt = now;
|
||||
this.updatedAt = now;
|
||||
}
|
||||
|
||||
@PreUpdate
|
||||
private void onUpdate() {
|
||||
this.updatedAt = Instant.now().truncatedTo(ChronoUnit.MILLIS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package ru.mtusi.messenger.model;
|
||||
|
||||
public enum AttachmentStatus {
|
||||
UPLOADING,
|
||||
QUEUED,
|
||||
PROCESSING,
|
||||
READY,
|
||||
FAILED,
|
||||
BROKEN
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package ru.mtusi.messenger.model;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.JoinTable;
|
||||
import jakarta.persistence.ManyToMany;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.OrderBy;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "chats")
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
public class Chat {
|
||||
|
||||
@Id
|
||||
@Column(nullable = false, updatable = false)
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@Column(nullable = false, length = 100)
|
||||
private String title;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@ManyToMany(fetch = FetchType.LAZY)
|
||||
@JoinTable(
|
||||
name = "chat_members",
|
||||
joinColumns = @JoinColumn(name = "chat_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "user_id"))
|
||||
private Set<User> members = new HashSet<>();
|
||||
|
||||
@OneToMany(
|
||||
mappedBy = "chat",
|
||||
fetch = FetchType.LAZY,
|
||||
cascade = CascadeType.ALL,
|
||||
orphanRemoval = true)
|
||||
@OrderBy("createdAt ASC, id ASC")
|
||||
private List<Message> messages = new ArrayList<>();
|
||||
|
||||
@PrePersist
|
||||
private void onCreate() {
|
||||
this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package ru.mtusi.messenger.model;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import org.hibernate.annotations.JdbcTypeCode;
|
||||
import org.hibernate.type.SqlTypes;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "idempotency_keys")
|
||||
@Getter
|
||||
@Setter
|
||||
public class IdempotencyKey {
|
||||
|
||||
@Id
|
||||
@Column(nullable = false, updatable = false)
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private UUID userId;
|
||||
|
||||
@Column(nullable = false, length = 16)
|
||||
private String method;
|
||||
|
||||
@Column(name = "chat_id", nullable = false)
|
||||
private UUID chatId;
|
||||
|
||||
@Column(name = "idempotency_key", nullable = false, length = 128)
|
||||
private String idempotencyKey;
|
||||
|
||||
@Column(name = "request_hash", nullable = false, length = 64)
|
||||
private String requestHash;
|
||||
|
||||
@Column(name = "status_code")
|
||||
private Short statusCode;
|
||||
|
||||
@JdbcTypeCode(SqlTypes.JSON)
|
||||
@Column(name = "response_body", columnDefinition = "jsonb")
|
||||
private String responseBody;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private Instant createdAt;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package ru.mtusi.messenger.model;
|
||||
|
||||
import jakarta.persistence.CollectionTable;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.ElementCollection;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.OrderColumn;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "messages")
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
public class Message {
|
||||
|
||||
@Id
|
||||
@Column(nullable = false, updatable = false)
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "chat_id", nullable = false)
|
||||
private Chat chat;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "sender_id", nullable = false)
|
||||
private User sender;
|
||||
|
||||
@Column(nullable = false, length = 4000)
|
||||
private String text;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@ElementCollection
|
||||
@CollectionTable(name = "message_attachments", joinColumns = @JoinColumn(name = "message_id"))
|
||||
@Column(name = "attachment_id")
|
||||
@OrderColumn(name = "attachment_order")
|
||||
private List<UUID> attachmentIds = new ArrayList<>();
|
||||
|
||||
@PrePersist
|
||||
private void onCreate() {
|
||||
this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package ru.mtusi.messenger.model;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "sessions")
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
public class Session {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@Column(name = "user_id", nullable = false)
|
||||
private UUID userId;
|
||||
|
||||
@Column(name = "token_hash", nullable = false, unique = true)
|
||||
private byte[] tokenHash;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private Instant expiresAt;
|
||||
|
||||
@Column(name = "revoked_at")
|
||||
private Instant revokedAt;
|
||||
|
||||
@PrePersist
|
||||
private void onCreate() {
|
||||
this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package ru.mtusi.messenger.model;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.ManyToMany;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class User {
|
||||
|
||||
@Id()
|
||||
@Column(nullable = false, updatable = false)
|
||||
@GeneratedValue(strategy = GenerationType.UUID)
|
||||
private UUID id;
|
||||
|
||||
@Column(nullable = false, unique = true, length = 32)
|
||||
private String username;
|
||||
|
||||
@Column(name = "display_name", nullable = false, length = 100)
|
||||
private String displayName;
|
||||
|
||||
@Column(name = "password_hash", nullable = false, length = 255)
|
||||
private String passwordHash;
|
||||
|
||||
@Column(name = "created_at", nullable = false, updatable = false)
|
||||
private Instant createdAt;
|
||||
|
||||
@ManyToMany(mappedBy = "members", fetch = FetchType.LAZY)
|
||||
private Set<Chat> chats = new HashSet<>();
|
||||
|
||||
@OneToMany(mappedBy = "sender", fetch = FetchType.LAZY)
|
||||
private Set<Message> messages = new HashSet<>();
|
||||
|
||||
@PrePersist
|
||||
private void onCreate() {
|
||||
this.createdAt = Instant.now().truncatedTo(ChronoUnit.MILLIS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import jakarta.persistence.LockModeType;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Lock;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
|
||||
import ru.mtusi.messenger.model.Attachment;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface AttachmentRepository extends JpaRepository<Attachment, UUID> {
|
||||
@Lock(LockModeType.PESSIMISTIC_READ)
|
||||
@Query("select attachment from Attachment attachment where attachment.id = :id")
|
||||
Optional<Attachment> findForMessage(UUID id);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import jakarta.persistence.LockModeType;
|
||||
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.EntityGraph;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Lock;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import ru.mtusi.messenger.model.Chat;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface ChatRepository extends JpaRepository<Chat, UUID> {
|
||||
|
||||
@Lock(LockModeType.PESSIMISTIC_WRITE)
|
||||
@Query("select c from Chat c where c.id = :chatId")
|
||||
Optional<Chat> findForMessageCreation(@Param("chatId") UUID chatId);
|
||||
|
||||
@EntityGraph(attributePaths = "members")
|
||||
@Query(
|
||||
"""
|
||||
select distinct c from Chat c
|
||||
join c.members m
|
||||
where m.id = :userId
|
||||
order by c.createdAt asc, c.id asc
|
||||
""")
|
||||
List<Chat> findPageByMember(@Param("userId") UUID userId, Pageable pageable);
|
||||
|
||||
@EntityGraph(attributePaths = "members")
|
||||
@Query(
|
||||
"""
|
||||
select distinct c from Chat c
|
||||
join c.members m
|
||||
where m.id = :userId
|
||||
and (c.createdAt > :cursorCreated
|
||||
or (c.createdAt = :cursorCreated and c.id > :cursorId))
|
||||
order by c.createdAt asc, c.id asc
|
||||
""")
|
||||
List<Chat> findPageByMemberAfterCursor(
|
||||
@Param("userId") UUID userId,
|
||||
@Param("cursorCreated") Instant cursorCreated,
|
||||
@Param("cursorId") UUID cursorId,
|
||||
Pageable pageable);
|
||||
|
||||
boolean existsByIdAndMembersId(UUID chatId, UUID userId);
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
import ru.mtusi.messenger.model.IdempotencyKey;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
@Repository
|
||||
public interface IdempotencyRepository extends JpaRepository<IdempotencyKey, UUID> {
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query(
|
||||
value =
|
||||
"""
|
||||
INSERT INTO idempotency_keys
|
||||
(user_id, method, chat_id, idempotency_key, request_hash, created_at)
|
||||
VALUES (:userId, :method, :chatId, :key, :hash, NOW())
|
||||
ON CONFLICT (user_id, method, chat_id, idempotency_key) DO NOTHING
|
||||
""",
|
||||
nativeQuery = true)
|
||||
int tryClaim(UUID userId, String method, UUID chatId, String key, String hash);
|
||||
|
||||
@Modifying(clearAutomatically = true, flushAutomatically = true)
|
||||
@Query(
|
||||
value =
|
||||
"""
|
||||
UPDATE idempotency_keys
|
||||
SET status_code = :statusCode,
|
||||
response_body = CAST(:body AS jsonb)
|
||||
WHERE user_id = :userId
|
||||
AND method = :method
|
||||
AND chat_id = :chatId
|
||||
AND idempotency_key = :key
|
||||
""",
|
||||
nativeQuery = true)
|
||||
int commitResponse(
|
||||
UUID userId, String method, UUID chatId, String key, int statusCode, String body);
|
||||
|
||||
Optional<IdempotencyKey> findByUserIdAndMethodAndChatIdAndIdempotencyKey(
|
||||
UUID userId, String method, UUID chatId, String idempotencyKey);
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.EntityGraph;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import ru.mtusi.messenger.model.Message;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface MessageRepository extends JpaRepository<Message, UUID> {
|
||||
|
||||
long countByChatId(UUID chatId);
|
||||
|
||||
@EntityGraph(attributePaths = "sender")
|
||||
@Query(
|
||||
"""
|
||||
select m from Message m
|
||||
where m.chat.id = :chatId
|
||||
order by m.createdAt asc, m.id asc
|
||||
""")
|
||||
List<Message> findPageByChat(@Param("chatId") UUID chatId, Pageable pageable);
|
||||
|
||||
@EntityGraph(attributePaths = "sender")
|
||||
@Query(
|
||||
"""
|
||||
select m from Message m
|
||||
where m.chat.id = :chatId
|
||||
and (m.createdAt > :cursorCreated
|
||||
or (m.createdAt = :cursorCreated and m.id > :cursorId))
|
||||
order by m.createdAt asc, m.id asc
|
||||
""")
|
||||
List<Message> findPageByChatAfterCursor(
|
||||
@Param("chatId") UUID chatId,
|
||||
@Param("cursorCreated") Instant cursorCreated,
|
||||
@Param("cursorId") UUID cursorId,
|
||||
Pageable pageable);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import ru.mtusi.messenger.model.Session;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface SessionRepository extends JpaRepository<Session, UUID> {
|
||||
Optional<Session> findByTokenHash(byte[] tokenHash);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package ru.mtusi.messenger.repository;
|
||||
|
||||
import jakarta.persistence.LockModeType;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Lock;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import ru.mtusi.messenger.model.User;
|
||||
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
public interface UserRepository extends JpaRepository<User, UUID> {
|
||||
|
||||
Optional<User> findByUsername(String username);
|
||||
|
||||
@Lock(LockModeType.PESSIMISTIC_READ)
|
||||
@Query("select u from User u where u.id in :ids")
|
||||
Set<User> findAllByIdForShare(@Param("ids") Set<UUID> ids);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package ru.mtusi.messenger.security;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import ru.mtusi.messenger.dto.ErrorErrorDTO;
|
||||
import ru.mtusi.messenger.exception.ApiErrorFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ApiAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
private final ApiErrorFactory errors;
|
||||
|
||||
@Override
|
||||
public void commence(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
AuthenticationException authException)
|
||||
throws IOException {
|
||||
boolean isLogin = "/api/v1/auth/sessions".equals(request.getRequestURI());
|
||||
String challenge =
|
||||
isLogin
|
||||
? "Basic realm=\"messenger\", charset=\"UTF-8\""
|
||||
: "Bearer realm=\"messenger\"";
|
||||
|
||||
errors.writeError(
|
||||
response,
|
||||
request,
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
challenge,
|
||||
ErrorErrorDTO.CodeEnum.UNAUTHORIZED,
|
||||
"No valid authentication");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package ru.mtusi.messenger.security;
|
||||
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Base64;
|
||||
|
||||
public record BasicCredentials(String username, String password) {
|
||||
|
||||
public static BasicCredentials parse(String header) {
|
||||
if (header == null || !header.regionMatches(true, 0, "Basic ", 0, 6)) {
|
||||
throw new UnauthorizedException("Basic authentication required");
|
||||
}
|
||||
String decoded;
|
||||
try {
|
||||
decoded =
|
||||
new String(
|
||||
Base64.getDecoder().decode(header.substring(6).trim()),
|
||||
StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new UnauthorizedException("Invalid Basic encoding");
|
||||
}
|
||||
int i = decoded.indexOf(':');
|
||||
if (i < 0) {
|
||||
throw new UnauthorizedException("Invalid Basic credentials");
|
||||
}
|
||||
return new BasicCredentials(decoded.substring(0, i), decoded.substring(i + 1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package ru.mtusi.messenger.security;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.authentication.AuthenticationManager;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.core.context.SecurityContext;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.security.oauth2.server.resource.web.BearerTokenResolver;
|
||||
import org.springframework.transaction.TransactionException;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import ru.mtusi.messenger.dto.ErrorErrorDTO;
|
||||
import ru.mtusi.messenger.exception.ApiErrorFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@RequiredArgsConstructor
|
||||
public class SessionAuthenticationFilter extends OncePerRequestFilter {
|
||||
private final BearerTokenResolver bearerTokenResolver;
|
||||
private final AuthenticationManager authenticationManager;
|
||||
private final ApiErrorFactory errors;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws ServletException, IOException {
|
||||
try {
|
||||
String token = bearerTokenResolver.resolve(request);
|
||||
if (token != null && !token.isBlank()) {
|
||||
try {
|
||||
Authentication auth =
|
||||
authenticationManager.authenticate(
|
||||
new SessionAuthenticationToken(token));
|
||||
SecurityContext context = SecurityContextHolder.createEmptyContext();
|
||||
context.setAuthentication(auth);
|
||||
SecurityContextHolder.setContext(context);
|
||||
} catch (DataAccessException | TransactionException e) {
|
||||
errors.writeError(
|
||||
response,
|
||||
request,
|
||||
HttpStatus.SERVICE_UNAVAILABLE,
|
||||
null,
|
||||
ErrorErrorDTO.CodeEnum.UNAVAILABLE,
|
||||
"Session storage unavailable");
|
||||
return;
|
||||
} catch (AuthenticationException e) {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
} finally {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package ru.mtusi.messenger.security;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.security.authentication.AuthenticationProvider;
|
||||
import org.springframework.security.authentication.BadCredentialsException;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.service.SessionService;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class SessionAuthenticationProvider implements AuthenticationProvider {
|
||||
private final SessionService sessionService;
|
||||
|
||||
@Override
|
||||
public Authentication authenticate(Authentication authentication)
|
||||
throws AuthenticationException {
|
||||
String token = (String) authentication.getCredentials();
|
||||
try {
|
||||
var rec = sessionService.requireActive(token);
|
||||
return new SessionAuthenticationToken(
|
||||
new SessionPrincipal(rec.userId(), rec.sessionId()));
|
||||
} catch (UnauthorizedException e) {
|
||||
throw new BadCredentialsException(e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean supports(Class<?> authentication) {
|
||||
return SessionAuthenticationToken.class.isAssignableFrom(authentication);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package ru.mtusi.messenger.security;
|
||||
|
||||
import org.springframework.security.authentication.AbstractAuthenticationToken;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class SessionAuthenticationToken extends AbstractAuthenticationToken {
|
||||
private final String rawToken;
|
||||
private final SessionPrincipal principal;
|
||||
|
||||
public SessionAuthenticationToken(String rawToken) {
|
||||
super(List.of());
|
||||
this.rawToken = rawToken;
|
||||
this.principal = null;
|
||||
setAuthenticated(false);
|
||||
}
|
||||
|
||||
public SessionAuthenticationToken(SessionPrincipal principal) {
|
||||
super(List.of());
|
||||
this.rawToken = null;
|
||||
this.principal = principal;
|
||||
setAuthenticated(true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getCredentials() {
|
||||
return rawToken;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPrincipal() {
|
||||
return principal;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package ru.mtusi.messenger.security;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record SessionPrincipal(UUID userId, UUID sessionId) {}
|
||||
@@ -0,0 +1,273 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import io.minio.GetObjectArgs;
|
||||
import io.minio.MinioClient;
|
||||
import io.minio.PutObjectArgs;
|
||||
import io.minio.RemoveObjectArgs;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import org.springframework.dao.DataAccessException;
|
||||
import org.springframework.http.ContentDisposition;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import ru.mtusi.messenger.config.properties.S3Properties;
|
||||
import ru.mtusi.messenger.dto.AttachmentDTO;
|
||||
import ru.mtusi.messenger.exception.ConflictException;
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
import ru.mtusi.messenger.exception.NotFoundException;
|
||||
import ru.mtusi.messenger.exception.PayloadTooLargeException;
|
||||
import ru.mtusi.messenger.exception.ServiceUnavailableException;
|
||||
import ru.mtusi.messenger.exception.StorageUnavailableException;
|
||||
import ru.mtusi.messenger.exception.UnsupportedMediaTypeException;
|
||||
import ru.mtusi.messenger.mapper.AttachmentMapper;
|
||||
import ru.mtusi.messenger.model.Attachment;
|
||||
import ru.mtusi.messenger.model.AttachmentStatus;
|
||||
import ru.mtusi.messenger.model.Chat;
|
||||
import ru.mtusi.messenger.model.User;
|
||||
import ru.mtusi.messenger.repository.AttachmentRepository;
|
||||
import ru.mtusi.messenger.telemetry.Telemetry;
|
||||
import ru.mtusi.messenger.validation.AttachmentValidator;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.Semaphore;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class AttachmentService {
|
||||
private final Telemetry telemetry;
|
||||
private final Semaphore uploads = new Semaphore(1, true);
|
||||
private final JdbcTemplate jdbc;
|
||||
private final ProcessingJobService jobs;
|
||||
private final AttachmentVariantService variants;
|
||||
private final UserService userService;
|
||||
private final ChatService chatService;
|
||||
private final MinioClient minio;
|
||||
private final AttachmentRepository attachmentRepository;
|
||||
private final S3Properties s3Props;
|
||||
private final AttachmentValidator validator;
|
||||
private final AttachmentMapper attachmentMapper;
|
||||
|
||||
@Transactional
|
||||
public AttachmentDTO upload(
|
||||
UUID chatId,
|
||||
UUID caller,
|
||||
String filename,
|
||||
HttpServletRequest request,
|
||||
String declaredType) {
|
||||
acquireUploadSlot();
|
||||
try {
|
||||
return performUpload(chatId, caller, filename, request, declaredType);
|
||||
} finally {
|
||||
uploads.release();
|
||||
}
|
||||
}
|
||||
|
||||
private void acquireUploadSlot() {
|
||||
try {
|
||||
if (!uploads.tryAcquire(30, TimeUnit.SECONDS))
|
||||
throw new ServiceUnavailableException("Upload capacity exhausted");
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new ServiceUnavailableException("Upload interrupted");
|
||||
}
|
||||
}
|
||||
|
||||
private AttachmentDTO performUpload(
|
||||
UUID chatId,
|
||||
UUID caller,
|
||||
String filename,
|
||||
HttpServletRequest request,
|
||||
String declaredType) {
|
||||
jdbc.execute("select pg_advisory_xact_lock_shared(741204)");
|
||||
Chat chat = chatService.getChat(caller, chatId);
|
||||
String safeFilename = validator.sanitizeFilename(filename);
|
||||
byte[] body = readBounded(request);
|
||||
String contentType = validator.validate(body, safeFilename);
|
||||
if (!contentType.equals(declaredType))
|
||||
throw new UnsupportedMediaTypeException("MIME mismatch");
|
||||
jobs.requireCapacity();
|
||||
String objectKey = "staging/" + UUID.randomUUID();
|
||||
String checksum =
|
||||
telemetry.dependency(
|
||||
"s3.staging.put", () -> uploadToS3(body, objectKey, contentType));
|
||||
return saveAttachmentQueued(
|
||||
objectKey, safeFilename, contentType, body, checksum, chat, caller);
|
||||
}
|
||||
|
||||
private byte[] readBounded(HttpServletRequest request) {
|
||||
try {
|
||||
byte[] bytes = request.getInputStream().readNBytes(10485761);
|
||||
if (bytes.length > 10485760) throw new PayloadTooLargeException("File exceeds limit");
|
||||
return bytes;
|
||||
} catch (IOException e) {
|
||||
throw new InvalidRequestException("Incomplete upload");
|
||||
}
|
||||
}
|
||||
|
||||
AttachmentDTO saveAttachmentQueued(
|
||||
String objectKey,
|
||||
String safeFilename,
|
||||
String contentType,
|
||||
byte[] body,
|
||||
String checksum,
|
||||
Chat chat,
|
||||
UUID caller) {
|
||||
try {
|
||||
Attachment attachment =
|
||||
buildAttachment(
|
||||
objectKey, safeFilename, contentType, body, checksum, chat, caller);
|
||||
attachment.setStatus(AttachmentStatus.QUEUED);
|
||||
attachmentRepository.saveAndFlush(attachment);
|
||||
jobs.enqueue(attachment.getId());
|
||||
return attachmentMapper.toDto(attachment);
|
||||
} catch (DataAccessException e) {
|
||||
compensateS3Upload(objectKey);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(
|
||||
readOnly = true,
|
||||
isolation = org.springframework.transaction.annotation.Isolation.REPEATABLE_READ)
|
||||
public AttachmentDTO getMetadata(UUID attachmentId, UUID userId) {
|
||||
Attachment attachment = requireAttachmentForMember(attachmentId, userId);
|
||||
AttachmentDTO result = attachmentMapper.toDto(attachment);
|
||||
result.setVariants(variants.metadata(attachment));
|
||||
return result;
|
||||
}
|
||||
|
||||
public DownloadedAttachment download(UUID attachmentId, UUID userId, String variant) {
|
||||
Attachment attachment = requireAttachmentForMember(attachmentId, userId);
|
||||
if (attachment.getStatus() != AttachmentStatus.READY)
|
||||
throw new ConflictException("Attachment not ready");
|
||||
return streamFromS3(attachment, variant);
|
||||
}
|
||||
|
||||
void compensateS3Upload(String objectKey) {
|
||||
try {
|
||||
minio.removeObject(
|
||||
RemoveObjectArgs.builder().bucket(s3Props.bucket()).object(objectKey).build());
|
||||
log.info("Compensated S3 upload: removed objectKey={}", objectKey);
|
||||
} catch (Exception e) {
|
||||
log.error(
|
||||
"Failed to compensate S3 upload for objectKey={}: {}",
|
||||
objectKey,
|
||||
e.getMessage(),
|
||||
e);
|
||||
}
|
||||
}
|
||||
|
||||
private String uploadToS3(byte[] body, String objectKey, String contentType) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance("SHA-256");
|
||||
try (var digestIn =
|
||||
new java.security.DigestInputStream(
|
||||
new java.io.ByteArrayInputStream(body), digest)) {
|
||||
minio.putObject(
|
||||
PutObjectArgs.builder().bucket(s3Props.bucket()).object(objectKey).stream(
|
||||
digestIn, (long) body.length, -1L)
|
||||
.contentType(contentType)
|
||||
.build());
|
||||
}
|
||||
return HexFormat.of().formatHex(digest.digest());
|
||||
} catch (Exception e) {
|
||||
log.error("S3 upload failed for objectKey: {}", objectKey, e);
|
||||
throw new StorageUnavailableException("S3 upload failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
private Attachment buildAttachment(
|
||||
String objectKey,
|
||||
String filename,
|
||||
String contentType,
|
||||
byte[] body,
|
||||
String checksum,
|
||||
Chat chat,
|
||||
UUID caller) {
|
||||
User owner = userService.getReferenceUserById(caller);
|
||||
return attachmentMapper.toEntity(
|
||||
objectKey, filename, contentType, (long) body.length, checksum, chat, owner);
|
||||
}
|
||||
|
||||
private Attachment requireAttachmentForMember(UUID attachmentId, UUID userId) {
|
||||
Attachment attachment =
|
||||
attachmentRepository
|
||||
.findById(attachmentId)
|
||||
.orElseThrow(() -> new NotFoundException("Attachment not found"));
|
||||
assertMember(attachment.getChat().getId(), userId);
|
||||
return attachment;
|
||||
}
|
||||
|
||||
private DownloadedAttachment streamFromS3(Attachment attachment, String variant) {
|
||||
var content = variants.content(attachment, variant);
|
||||
try {
|
||||
var stream =
|
||||
minio.getObject(
|
||||
GetObjectArgs.builder()
|
||||
.bucket(s3Props.bucket())
|
||||
.object(content.objectKey())
|
||||
.build());
|
||||
return new DownloadedAttachment(
|
||||
stream, content.contentType(), attachment.getFilename());
|
||||
} catch (Exception e) {
|
||||
throw translateS3Exception(e, attachment.getId(), attachment.getObjectKey());
|
||||
}
|
||||
}
|
||||
|
||||
private RuntimeException translateS3Exception(
|
||||
Exception e, UUID attachmentId, String objectKey) {
|
||||
if (e instanceof io.minio.errors.ErrorResponseException minioEx) {
|
||||
if ("NoSuchKey".equals(minioEx.errorResponse().code())) {
|
||||
log.warn("S3 object missing for attachment {}", attachmentId);
|
||||
return new NotFoundException("Attachment content not found");
|
||||
}
|
||||
}
|
||||
log.error("S3 download failed for {}", objectKey, e);
|
||||
return new StorageUnavailableException("S3 download failed", e);
|
||||
}
|
||||
|
||||
private void assertMember(UUID chatId, UUID userId) {
|
||||
boolean isMember = chatService.existsByIdAndMembersId(chatId, userId);
|
||||
if (!isMember) {
|
||||
throw new NotFoundException("Attachment not found");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(
|
||||
readOnly = true,
|
||||
isolation = org.springframework.transaction.annotation.Isolation.READ_COMMITTED)
|
||||
public ResponseEntity<byte[]> downloadResponse(UUID id, UUID user, String variant) {
|
||||
jdbc.execute("SELECT pg_advisory_xact_lock_shared(741204)");
|
||||
var file = download(id, user, variant);
|
||||
try (var in = file.stream()) {
|
||||
return ResponseEntity.ok()
|
||||
.contentType(MediaType.parseMediaType(file.contentType()))
|
||||
.header(
|
||||
"Content-Disposition",
|
||||
ContentDisposition.attachment()
|
||||
.filename(file.filename(), StandardCharsets.UTF_8)
|
||||
.build()
|
||||
.toString())
|
||||
.body(in.readNBytes(10485761));
|
||||
} catch (IOException e) {
|
||||
throw new StorageUnavailableException("Download failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
public record DownloadedAttachment(InputStream stream, String contentType, String filename) {}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import ru.mtusi.messenger.dto.VariantDTO;
|
||||
import ru.mtusi.messenger.exception.NotFoundException;
|
||||
import ru.mtusi.messenger.model.Attachment;
|
||||
import ru.mtusi.messenger.model.AttachmentStatus;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AttachmentVariantService {
|
||||
private final JdbcTemplate jdbc;
|
||||
|
||||
public List<VariantDTO> metadata(Attachment attachment) {
|
||||
if (attachment.getStatus() != AttachmentStatus.READY) return List.of();
|
||||
return jdbc.query(
|
||||
"""
|
||||
SELECT * FROM attachment_variants
|
||||
WHERE attachment_id = ? AND pipeline_version = ? ORDER BY name
|
||||
""",
|
||||
(row, index) ->
|
||||
new VariantDTO(
|
||||
VariantDTO.NameEnum.fromValue(row.getString("name")),
|
||||
VariantDTO.ContentTypeEnum.fromValue(row.getString("content_type")),
|
||||
row.getLong("size_bytes"),
|
||||
row.getInt("width"),
|
||||
row.getInt("height"),
|
||||
row.getString("sha256")),
|
||||
attachment.getId(),
|
||||
attachment.getPipelineVersion());
|
||||
}
|
||||
|
||||
public Content content(Attachment attachment, String variant) {
|
||||
if ("original".equals(variant))
|
||||
return new Content(attachment.getObjectKey(), attachment.getContentType());
|
||||
List<Content> rows =
|
||||
jdbc.query(
|
||||
"""
|
||||
SELECT object_key, content_type FROM attachment_variants
|
||||
WHERE attachment_id = ? AND pipeline_version = ? AND name = ?
|
||||
""",
|
||||
(row, index) -> new Content(row.getString(1), row.getString(2)),
|
||||
attachment.getId(),
|
||||
attachment.getPipelineVersion(),
|
||||
variant);
|
||||
if (rows.isEmpty()) throw new NotFoundException("Variant not found");
|
||||
return rows.getFirst();
|
||||
}
|
||||
|
||||
public record Content(String objectKey, String contentType) {}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import ru.mtusi.messenger.dto.SessionDTO;
|
||||
import ru.mtusi.messenger.dto.UserDTO;
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.security.BasicCredentials;
|
||||
import ru.mtusi.messenger.security.SessionPrincipal;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AuthService {
|
||||
private final UserService userService;
|
||||
private final SessionService sessionService;
|
||||
|
||||
public SessionDTO login(String authorizationHeader, long contentLength) {
|
||||
if (contentLength > 0) {
|
||||
throw new InvalidRequestException("Request body is not allowed");
|
||||
}
|
||||
var creds = BasicCredentials.parse(authorizationHeader);
|
||||
UserDTO userDTO = userService.authenticate(creds.username(), creds.password());
|
||||
return sessionService.createSession(userDTO);
|
||||
}
|
||||
|
||||
public void logout() {
|
||||
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
|
||||
if (auth == null || !(auth.getPrincipal() instanceof SessionPrincipal sp)) {
|
||||
throw new UnauthorizedException("No active session");
|
||||
}
|
||||
sessionService.revoke(sp.sessionId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import ru.mtusi.messenger.dto.ChatDTO;
|
||||
import ru.mtusi.messenger.dto.ChatPageDTO;
|
||||
import ru.mtusi.messenger.dto.CreateChatDTO;
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
import ru.mtusi.messenger.exception.NotFoundException;
|
||||
import ru.mtusi.messenger.mapper.ChatMapper;
|
||||
import ru.mtusi.messenger.model.Chat;
|
||||
import ru.mtusi.messenger.model.User;
|
||||
import ru.mtusi.messenger.repository.ChatRepository;
|
||||
import ru.mtusi.messenger.util.CursorCodec;
|
||||
import ru.mtusi.messenger.validation.ChatValidator;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class ChatService {
|
||||
private final ChatMapper chatMapper;
|
||||
private final ChatValidator chatValidator;
|
||||
private final ChatRepository chatRepository;
|
||||
|
||||
@Transactional
|
||||
public ChatDTO createChat(UUID caller, CreateChatDTO createChatDTO) {
|
||||
Set<User> members = chatValidator.validateCreate(caller, createChatDTO);
|
||||
Chat chat = buildChat(createChatDTO, members);
|
||||
chat = persistChat(chat);
|
||||
return chatMapper.toChatDto(chat);
|
||||
}
|
||||
|
||||
private Chat buildChat(CreateChatDTO createChatDTO, Set<User> members) {
|
||||
Chat chat = chatMapper.toChat(createChatDTO);
|
||||
chat.setMembers(members);
|
||||
return chat;
|
||||
}
|
||||
|
||||
private Chat persistChat(Chat chat) {
|
||||
try {
|
||||
return chatRepository.saveAndFlush(chat);
|
||||
} catch (DataIntegrityViolationException e) {
|
||||
throw new InvalidRequestException("Cannot create chat: invalid data");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ChatDTO getChatDTO(UUID caller, UUID chatId) {
|
||||
Chat chat = requireChatForMember(caller, chatId);
|
||||
return chatMapper.toChatDto(chat);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public Chat getChat(UUID caller, UUID chatId) {
|
||||
return requireChatForMember(caller, chatId);
|
||||
}
|
||||
|
||||
private Chat requireChatForMember(UUID caller, UUID chatId) {
|
||||
Chat chat =
|
||||
chatRepository
|
||||
.findById(chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Chat not found"));
|
||||
if (chat.getMembers().stream().noneMatch(m -> m.getId().equals(caller))) {
|
||||
throw new NotFoundException("Chat not found");
|
||||
}
|
||||
return chat;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public ChatPageDTO listChats(UUID userId, Integer limit, String cursor) {
|
||||
int size = resolveSize(limit);
|
||||
CursorCodec.Cursor decoded = parseChatsCursor(cursor);
|
||||
List<Chat> rows = loadChatPage(userId, decoded, size);
|
||||
return buildPage(rows, size);
|
||||
}
|
||||
|
||||
private int resolveSize(Integer limit) {
|
||||
return (limit == null) ? 50 : limit;
|
||||
}
|
||||
|
||||
private List<Chat> loadChatPage(UUID userId, CursorCodec.Cursor cursor, int size) {
|
||||
if (cursor == null) {
|
||||
return chatRepository.findPageByMember(userId, Pageable.ofSize(size + 1));
|
||||
}
|
||||
return chatRepository.findPageByMemberAfterCursor(
|
||||
userId,
|
||||
cursor.boundary().createdAt(),
|
||||
cursor.boundary().id(),
|
||||
Pageable.ofSize(size + 1));
|
||||
}
|
||||
|
||||
private CursorCodec.Cursor parseChatsCursor(String cursor) {
|
||||
if (cursor == null) return null;
|
||||
if (cursor.isEmpty()) throw new InvalidRequestException("Cursor must not be empty");
|
||||
CursorCodec.Cursor decoded = CursorCodec.decode(cursor);
|
||||
if (decoded.scopeId() != null) throw new InvalidRequestException("Invalid cursor");
|
||||
return decoded;
|
||||
}
|
||||
|
||||
private ChatPageDTO buildPage(List<Chat> rows, int size) {
|
||||
List<ChatDTO> items = rows.stream().limit(size).map(chatMapper::toChatDto).toList();
|
||||
|
||||
ChatPageDTO page = new ChatPageDTO();
|
||||
page.setItems(items);
|
||||
page.setNextCursor(buildNextCursor(rows, size));
|
||||
return page;
|
||||
}
|
||||
|
||||
private String buildNextCursor(List<Chat> rows, int size) {
|
||||
if (rows.size() <= size) {
|
||||
return null;
|
||||
}
|
||||
Chat last = rows.get(size - 1);
|
||||
return CursorCodec.encode(null, boundaryOf(last));
|
||||
}
|
||||
|
||||
private CursorCodec.PageBoundary boundaryOf(Chat chat) {
|
||||
return new CursorCodec.PageBoundary(chat.getCreatedAt(), chat.getId());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public boolean existsByIdAndMembersId(UUID chatId, UUID userId) {
|
||||
return chatRepository.existsByIdAndMembersId(chatId, userId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import ru.mtusi.messenger.dto.HealthDTO;
|
||||
import ru.mtusi.messenger.exception.ServiceUnavailableException;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class HealthService {
|
||||
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final DataSource dataSource;
|
||||
private final io.minio.MinioClient minio;
|
||||
private final ru.mtusi.messenger.config.properties.S3Properties s3;
|
||||
|
||||
public HealthDTO readiness() {
|
||||
requirePoolAvailable();
|
||||
requireDatabaseReachable();
|
||||
try {
|
||||
if (!minio.bucketExists(
|
||||
io.minio.BucketExistsArgs.builder().bucket(s3.bucket()).build()))
|
||||
throw new ServiceUnavailableException("Storage unavailable");
|
||||
} catch (Exception e) {
|
||||
throw new ServiceUnavailableException("Storage unavailable");
|
||||
}
|
||||
return ok();
|
||||
}
|
||||
|
||||
public HealthDTO liveness() {
|
||||
return ok();
|
||||
}
|
||||
|
||||
private void requirePoolAvailable() {
|
||||
if (dataSource instanceof HikariDataSource hikari) {
|
||||
var pool = hikari.getHikariPoolMXBean();
|
||||
if (pool != null && pool.getActiveConnections() >= hikari.getMaximumPoolSize()) {
|
||||
throw new ServiceUnavailableException("Database connection pool exhausted");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void requireDatabaseReachable() {
|
||||
try {
|
||||
jdbcTemplate.queryForObject("SELECT 1", Integer.class);
|
||||
} catch (Exception e) {
|
||||
throw new ServiceUnavailableException("Database unavailable");
|
||||
}
|
||||
}
|
||||
|
||||
private HealthDTO ok() {
|
||||
HealthDTO h = new HealthDTO();
|
||||
h.setStatus(HealthDTO.StatusEnum.OK);
|
||||
return h;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import ru.mtusi.messenger.exception.ConflictException;
|
||||
import ru.mtusi.messenger.model.IdempotencyKey;
|
||||
import ru.mtusi.messenger.repository.IdempotencyRepository;
|
||||
import ru.mtusi.messenger.util.converter.IdempotencyPayloadConverter;
|
||||
import ru.mtusi.messenger.validation.IdempotencyValidator;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class IdempotencyService {
|
||||
|
||||
private final IdempotencyRepository idempotencyRepository;
|
||||
private final IdempotencyPayloadConverter converter;
|
||||
private final IdempotencyValidator validator;
|
||||
|
||||
@Transactional
|
||||
public <T> T execute(
|
||||
UUID userId,
|
||||
String method,
|
||||
UUID chatId,
|
||||
String key,
|
||||
Object requestBody,
|
||||
Class<T> responseType,
|
||||
Supplier<T> action) {
|
||||
validator.validateKey(key);
|
||||
String hash = hashRequest(requestBody);
|
||||
|
||||
int claimed = idempotencyRepository.tryClaim(userId, method, chatId, key, hash);
|
||||
if (claimed == 0) {
|
||||
return replay(userId, method, chatId, key, hash, responseType);
|
||||
}
|
||||
|
||||
T result = action.get();
|
||||
idempotencyRepository.commitResponse(
|
||||
userId, method, chatId, key, 201, converter.toJson(result));
|
||||
return result;
|
||||
}
|
||||
|
||||
private <T> T replay(
|
||||
UUID userId,
|
||||
String method,
|
||||
UUID chatId,
|
||||
String key,
|
||||
String hash,
|
||||
Class<T> responseType) {
|
||||
IdempotencyKey stored =
|
||||
idempotencyRepository
|
||||
.findByUserIdAndMethodAndChatIdAndIdempotencyKey(
|
||||
userId, method, chatId, key)
|
||||
.orElseThrow(
|
||||
() ->
|
||||
new IllegalStateException(
|
||||
"Idempotency row not visible after conflict"));
|
||||
if (!stored.getRequestHash().equals(hash))
|
||||
throw new ConflictException("Idempotency-Key reused with a different request body");
|
||||
if (stored.getStatusCode() == null || stored.getStatusCode() != 201)
|
||||
throw new ConflictException("Idempotency-Key has unexpected status");
|
||||
return converter.fromJson(stored.getResponseBody(), responseType);
|
||||
}
|
||||
|
||||
private String hashRequest(Object body) {
|
||||
try {
|
||||
byte[] digest =
|
||||
MessageDigest.getInstance("SHA-256")
|
||||
.digest(converter.toJson(body).getBytes(StandardCharsets.UTF_8));
|
||||
return HexFormat.of().formatHex(digest);
|
||||
} catch (Exception e) {
|
||||
throw new IllegalStateException("Cannot hash request body", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import ru.mtusi.messenger.config.properties.AppProperties;
|
||||
import ru.mtusi.messenger.dto.CreateMessageDTO;
|
||||
import ru.mtusi.messenger.dto.MessageDTO;
|
||||
import ru.mtusi.messenger.dto.MessagePageDTO;
|
||||
import ru.mtusi.messenger.exception.ConflictException;
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
import ru.mtusi.messenger.exception.NotFoundException;
|
||||
import ru.mtusi.messenger.exception.PayloadTooLargeException;
|
||||
import ru.mtusi.messenger.mapper.MessageMapper;
|
||||
import ru.mtusi.messenger.model.AttachmentStatus;
|
||||
import ru.mtusi.messenger.model.Chat;
|
||||
import ru.mtusi.messenger.model.Message;
|
||||
import ru.mtusi.messenger.model.User;
|
||||
import ru.mtusi.messenger.repository.AttachmentRepository;
|
||||
import ru.mtusi.messenger.repository.ChatRepository;
|
||||
import ru.mtusi.messenger.repository.MessageRepository;
|
||||
import ru.mtusi.messenger.util.CursorCodec;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class MessageService {
|
||||
private final AttachmentRepository attachments;
|
||||
private final IdempotencyService idempotencyService;
|
||||
private final MessageRepository messageRepository;
|
||||
private final ChatRepository chatRepository;
|
||||
private final ChatService chatService;
|
||||
private final UserService userService;
|
||||
private final MessageMapper messageMapper;
|
||||
private final AppProperties appProperties;
|
||||
|
||||
@Transactional
|
||||
public MessageDTO createMessage(
|
||||
UUID senderId, UUID chatId, CreateMessageDTO dto, String idempotencyKey) {
|
||||
Chat chat = chatService.getChat(senderId, chatId);
|
||||
|
||||
return idempotencyService.execute(
|
||||
senderId,
|
||||
"POST",
|
||||
chatId,
|
||||
idempotencyKey,
|
||||
dto,
|
||||
MessageDTO.class,
|
||||
() -> doCreate(senderId, chatId, dto, chat));
|
||||
}
|
||||
|
||||
private MessageDTO doCreate(UUID senderId, UUID chatId, CreateMessageDTO dto, Chat chat) {
|
||||
validateCreate(chatId, dto);
|
||||
requireHistoryCapacity(chatId);
|
||||
User sender = userService.getReferenceUserById(senderId);
|
||||
Message message = buildMessage(dto, sender, chat);
|
||||
try {
|
||||
message = messageRepository.saveAndFlush(message);
|
||||
} catch (DataIntegrityViolationException e) {
|
||||
throw new NotFoundException("Cannot create message: referenced entity is missing");
|
||||
}
|
||||
log.info("Created message id={} in chat={}", message.getId(), chatId);
|
||||
return messageMapper.toMessageDTO(message);
|
||||
}
|
||||
|
||||
private void validateCreate(UUID chatId, CreateMessageDTO dto) {
|
||||
if (dto.getText() == null
|
||||
|| (dto.getText().isBlank()
|
||||
&& (dto.getAttachmentIds() == null || dto.getAttachmentIds().isEmpty()))) {
|
||||
throw new InvalidRequestException("Empty text");
|
||||
}
|
||||
var ids = dto.getAttachmentIds();
|
||||
if (ids == null
|
||||
|| ids.size() > 10
|
||||
|| ids.contains(null)
|
||||
|| new java.util.HashSet<>(ids).size() != ids.size()
|
||||
|| dto.getText().codePointCount(0, dto.getText().length()) > 4000) {
|
||||
throw new InvalidRequestException("Invalid message");
|
||||
}
|
||||
validateAttachments(chatId, ids);
|
||||
}
|
||||
|
||||
private void validateAttachments(UUID chatId, List<UUID> ids) {
|
||||
for (UUID id : ids.stream().sorted().toList()) {
|
||||
var attachment =
|
||||
attachments
|
||||
.findForMessage(id)
|
||||
.filter(a -> a.getChat().getId().equals(chatId))
|
||||
.orElseThrow(() -> new NotFoundException("Attachment not found"));
|
||||
if ((attachment.getStatus() == AttachmentStatus.FAILED
|
||||
|| attachment.getStatus() == AttachmentStatus.BROKEN)) {
|
||||
throw new ConflictException("Attachment not ready");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void requireHistoryCapacity(UUID chatId) {
|
||||
chatRepository
|
||||
.findForMessageCreation(chatId)
|
||||
.orElseThrow(() -> new NotFoundException("Chat not found"));
|
||||
if (messageRepository.countByChatId(chatId) >= appProperties.maxMessagesPerChat()) {
|
||||
throw new PayloadTooLargeException("Chat history limit reached");
|
||||
}
|
||||
}
|
||||
|
||||
private Message buildMessage(CreateMessageDTO createMessageDTO, User sender, Chat chat) {
|
||||
Message message = messageMapper.toMessage(createMessageDTO);
|
||||
message.setChat(chat);
|
||||
message.setSender(sender);
|
||||
return message;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public MessagePageDTO listMessages(UUID userId, UUID chatId, Integer limit, String cursor) {
|
||||
int size = (limit == null) ? 50 : limit;
|
||||
chatService.getChatDTO(userId, chatId);
|
||||
CursorCodec.Cursor decoded = parseMessagesCursor(cursor, chatId);
|
||||
List<Message> rows =
|
||||
(decoded == null)
|
||||
? messageRepository.findPageByChat(chatId, Pageable.ofSize(size + 1))
|
||||
: messageRepository.findPageByChatAfterCursor(
|
||||
chatId,
|
||||
decoded.boundary().createdAt(),
|
||||
decoded.boundary().id(),
|
||||
Pageable.ofSize(size + 1));
|
||||
return buildPage(rows, size, chatId);
|
||||
}
|
||||
|
||||
private CursorCodec.Cursor parseMessagesCursor(String cursor, UUID chatId) {
|
||||
if (cursor == null) return null;
|
||||
if (cursor.isEmpty()) throw new InvalidRequestException("Cursor must not be empty");
|
||||
CursorCodec.Cursor decoded = CursorCodec.decode(cursor);
|
||||
if (decoded.scopeId() == null || !decoded.scopeId().equals(chatId))
|
||||
throw new InvalidRequestException("Cursor from another chat");
|
||||
return decoded;
|
||||
}
|
||||
|
||||
private MessagePageDTO buildPage(List<Message> rows, int size, UUID chatId) {
|
||||
List<MessageDTO> items =
|
||||
rows.stream().limit(size).map(messageMapper::toMessageDTO).toList();
|
||||
|
||||
MessagePageDTO page = new MessagePageDTO();
|
||||
page.setItems(items);
|
||||
page.setNextCursor(buildNextCursor(rows, size, chatId));
|
||||
return page;
|
||||
}
|
||||
|
||||
private String buildNextCursor(List<Message> rows, int size, UUID chatId) {
|
||||
if (rows.size() <= size) {
|
||||
return null;
|
||||
}
|
||||
Message last = rows.get(size - 1);
|
||||
return CursorCodec.encode(
|
||||
chatId, new CursorCodec.PageBoundary(last.getCreatedAt(), last.getId()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import ru.mtusi.messenger.exception.ServiceUnavailableException;
|
||||
import ru.mtusi.messenger.telemetry.Telemetry;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class ProcessingJobService {
|
||||
private final Telemetry telemetry;
|
||||
private final JdbcTemplate jdbc;
|
||||
|
||||
@Value("${pipeline.max-pending:100}")
|
||||
private int maxPending;
|
||||
|
||||
@Value("${pipeline.max-attempts:5}")
|
||||
private int maxAttempts;
|
||||
|
||||
@Transactional(propagation = Propagation.MANDATORY)
|
||||
public void requireCapacity() {
|
||||
jdbc.execute("SELECT pg_advisory_xact_lock(741205)");
|
||||
Long pending =
|
||||
jdbc.queryForObject(
|
||||
"SELECT count(*) FROM processing_jobs WHERE status IN"
|
||||
+ " ('QUEUED','PROCESSING')",
|
||||
Long.class);
|
||||
if (pending == null || pending >= maxPending) {
|
||||
throw new ServiceUnavailableException("Processing queue capacity exhausted");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(propagation = Propagation.MANDATORY)
|
||||
public void enqueue(UUID attachmentId) {
|
||||
var context = telemetry.carrier();
|
||||
jdbc.update(
|
||||
"""
|
||||
WITH job AS (
|
||||
INSERT INTO processing_jobs(attachment_id, pipeline_version, attempt_limit)
|
||||
VALUES (?, 1, ?) RETURNING *
|
||||
)
|
||||
INSERT INTO processing_outbox(job_id, payload)
|
||||
SELECT job_id, jsonb_strip_nulls(jsonb_build_object('schema_version',1,'job_id',job_id,
|
||||
'type','attachment.process.v1','attachment_id',attachment_id,
|
||||
'pipeline_version',pipeline_version,'attempt',1,
|
||||
'created_at',to_char(created_at AT TIME ZONE 'UTC','YYYY-MM-DD"T"HH24:MI:SS.MS"Z"'),
|
||||
'traceparent',CAST(? AS text),'tracestate',CAST(? AS text)))
|
||||
FROM job
|
||||
""",
|
||||
attachmentId,
|
||||
maxAttempts,
|
||||
context.get("traceparent"),
|
||||
context.get("tracestate"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import org.springframework.cache.Cache;
|
||||
import org.springframework.cache.CacheManager;
|
||||
import org.springframework.cache.annotation.CacheEvict;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import ru.mtusi.messenger.cache.CacheHealthTracker;
|
||||
import ru.mtusi.messenger.repository.SessionRepository;
|
||||
import ru.mtusi.messenger.telemetry.Telemetry;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class SessionCacheService {
|
||||
private final Telemetry telemetry;
|
||||
|
||||
public static final String SESSIONS = "sessions";
|
||||
|
||||
private final SessionRepository sessionRepository;
|
||||
private final CacheManager cacheManager;
|
||||
private final CacheHealthTracker cacheHealthTracker;
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public SessionService.SessionRecord lookupByHash(String hex) {
|
||||
byte[] hash = hexToBytes(hex);
|
||||
return telemetry.dependency(
|
||||
"postgres.session.lookup",
|
||||
() ->
|
||||
sessionRepository
|
||||
.findByTokenHash(hash)
|
||||
.filter(s -> s.getRevokedAt() == null)
|
||||
.map(
|
||||
s ->
|
||||
new SessionService.SessionRecord(
|
||||
s.getId(), s.getUserId(), s.getExpiresAt()))
|
||||
.orElse(null));
|
||||
}
|
||||
|
||||
@CacheEvict(value = SESSIONS, key = "#hex")
|
||||
public void evict(String hex) {}
|
||||
|
||||
public void dropCacheIfStale() {
|
||||
if (!cacheHealthTracker.consumeStale()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Cache cache = cacheManager.getCache(SESSIONS);
|
||||
if (cache != null) {
|
||||
cache.clear();
|
||||
}
|
||||
log.info("Cache '{}' cleared after stale flag", SESSIONS);
|
||||
} catch (RuntimeException e) {
|
||||
log.warn("Cache clear failed: {}", e.getMessage());
|
||||
cacheHealthTracker.markStale();
|
||||
}
|
||||
}
|
||||
|
||||
private static byte[] hexToBytes(String hex) {
|
||||
int len = hex.length();
|
||||
byte[] out = new byte[len / 2];
|
||||
for (int i = 0; i < len; i += 2) {
|
||||
out[i / 2] =
|
||||
(byte)
|
||||
((Character.digit(hex.charAt(i), 16) << 4)
|
||||
+ Character.digit(hex.charAt(i + 1), 16));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import ru.mtusi.messenger.config.properties.SessionProperties;
|
||||
import ru.mtusi.messenger.dto.SessionDTO;
|
||||
import ru.mtusi.messenger.dto.UserDTO;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.mapper.SessionMapper;
|
||||
import ru.mtusi.messenger.model.Session;
|
||||
import ru.mtusi.messenger.repository.SessionRepository;
|
||||
import ru.mtusi.messenger.util.TokenGenerator;
|
||||
import ru.mtusi.messenger.util.TokenHasher;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.UUID;
|
||||
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
@Service
|
||||
public class SessionService {
|
||||
private final TokenGenerator tokenGenerator;
|
||||
private final TokenHasher tokenHasher;
|
||||
private final SessionProperties sessionProperties;
|
||||
private final SessionRepository sessionRepository;
|
||||
private final SessionMapper sessionMapper;
|
||||
private final SessionCacheService sessionCacheService;
|
||||
|
||||
@Transactional
|
||||
public SessionDTO createSession(UserDTO userDTO) {
|
||||
String token = tokenGenerator.generate();
|
||||
Session session = sessionRepository.save(buildSession(userDTO, token));
|
||||
return sessionMapper.toSessionDTO(session, token, userDTO);
|
||||
}
|
||||
|
||||
public SessionRecord requireActive(String token) {
|
||||
sessionCacheService.dropCacheIfStale();
|
||||
String hex = tokenHasher.hash(token);
|
||||
SessionRecord record = sessionCacheService.lookupByHash(hex);
|
||||
requireNotExpired(record, hex);
|
||||
return record;
|
||||
}
|
||||
|
||||
private void requireNotExpired(SessionRecord record, String hex) {
|
||||
if (record == null || isExpired(record)) {
|
||||
sessionCacheService.evict(hex);
|
||||
throw new UnauthorizedException("Invalid or expired session");
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isExpired(SessionRecord record) {
|
||||
return record.expiresAt().isBefore(Instant.now());
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void revoke(UUID sessionId) {
|
||||
sessionRepository.findById(sessionId).ifPresent(this::markRevokedAndEvict);
|
||||
}
|
||||
|
||||
private void markRevokedAndEvict(Session session) {
|
||||
if (session.getRevokedAt() == null) {
|
||||
session.setRevokedAt(Instant.now().truncatedTo(ChronoUnit.MILLIS));
|
||||
}
|
||||
sessionCacheService.evict(tokenHasher.hash(session.getTokenHash()));
|
||||
}
|
||||
|
||||
private Session buildSession(UserDTO userDTO, String token) {
|
||||
Session session = new Session();
|
||||
session.setUserId(userDTO.getId());
|
||||
session.setTokenHash(tokenHasher.sha256(token));
|
||||
session.setExpiresAt(
|
||||
Instant.now().plus(sessionProperties.ttl()).truncatedTo(ChronoUnit.MILLIS));
|
||||
return session;
|
||||
}
|
||||
|
||||
public record SessionRecord(UUID sessionId, UUID userId, Instant expiresAt) {}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package ru.mtusi.messenger.service;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import org.springframework.dao.DataIntegrityViolationException;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import ru.mtusi.messenger.dto.CreateUserDTO;
|
||||
import ru.mtusi.messenger.dto.UserDTO;
|
||||
import ru.mtusi.messenger.exception.ConflictException;
|
||||
import ru.mtusi.messenger.exception.NotFoundException;
|
||||
import ru.mtusi.messenger.exception.UnauthorizedException;
|
||||
import ru.mtusi.messenger.mapper.UserMapper;
|
||||
import ru.mtusi.messenger.model.User;
|
||||
import ru.mtusi.messenger.repository.UserRepository;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class UserService {
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final UserMapper userMapper;
|
||||
private final UserRepository userRepository;
|
||||
|
||||
@Transactional
|
||||
public Set<User> requireUsers(Collection<UUID> ids) {
|
||||
Set<UUID> uniqueIds = new HashSet<>(ids);
|
||||
Set<User> users = userRepository.findAllByIdForShare(uniqueIds);
|
||||
if (users.size() != uniqueIds.size()) {
|
||||
throw new NotFoundException("Users not found: " + findMissing(uniqueIds, users));
|
||||
}
|
||||
return users;
|
||||
}
|
||||
|
||||
private Set<UUID> findMissing(Set<UUID> requested, Set<User> found) {
|
||||
Set<UUID> foundIds = found.stream().map(User::getId).collect(Collectors.toSet());
|
||||
|
||||
Set<UUID> missing = new HashSet<>(requested);
|
||||
missing.removeAll(foundIds);
|
||||
return missing;
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public UserDTO authenticate(String username, String password) {
|
||||
User user =
|
||||
userRepository
|
||||
.findByUsername(username)
|
||||
.orElseThrow(() -> new UnauthorizedException("Bad credentials"));
|
||||
|
||||
if (!passwordEncoder.matches(password, user.getPasswordHash())) {
|
||||
throw new UnauthorizedException("Bad credentials");
|
||||
}
|
||||
return userMapper.toUserDto(user);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public UserDTO registerUser(CreateUserDTO createUserDTO) {
|
||||
User user = userMapper.toUser(createUserDTO);
|
||||
user.setPasswordHash(passwordEncoder.encode(createUserDTO.getPassword()));
|
||||
try {
|
||||
return userMapper.toUserDto(userRepository.saveAndFlush(user));
|
||||
} catch (DataIntegrityViolationException exception) {
|
||||
throw new ConflictException("Username already exists");
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public UserDTO currentUser(UUID userId) {
|
||||
return userMapper.toUserDto(
|
||||
userRepository
|
||||
.findById(userId)
|
||||
.orElseThrow(() -> new NotFoundException("User not found")));
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public User getReferenceUserById(UUID senderId) {
|
||||
return userRepository.getReferenceById(senderId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
package ru.mtusi.messenger.telemetry;
|
||||
|
||||
import com.sun.management.OperatingSystemMXBean;
|
||||
import com.zaxxer.hikari.HikariDataSource;
|
||||
|
||||
import io.opentelemetry.api.OpenTelemetry;
|
||||
import io.opentelemetry.api.common.AttributeKey;
|
||||
import io.opentelemetry.api.common.Attributes;
|
||||
import io.opentelemetry.api.logs.Severity;
|
||||
import io.opentelemetry.api.trace.Span;
|
||||
import io.opentelemetry.api.trace.SpanKind;
|
||||
import io.opentelemetry.api.trace.StatusCode;
|
||||
import io.opentelemetry.context.Context;
|
||||
import io.opentelemetry.context.propagation.TextMapGetter;
|
||||
import io.opentelemetry.context.propagation.TextMapSetter;
|
||||
import io.opentelemetry.sdk.OpenTelemetrySdk;
|
||||
import io.opentelemetry.sdk.autoconfigure.AutoConfiguredOpenTelemetrySdk;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Collections;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
|
||||
@Component
|
||||
public class Telemetry implements AutoCloseable {
|
||||
private static final String SCOPE = "ru.mtusi.messenger";
|
||||
private static final TextMapSetter<Map<String, String>> SETTER = Map::put;
|
||||
private static final TextMapGetter<HttpServletRequest> HEADERS =
|
||||
new TextMapGetter<>() {
|
||||
@Override
|
||||
public Iterable<String> keys(HttpServletRequest request) {
|
||||
return Collections.list(request.getHeaderNames());
|
||||
}
|
||||
|
||||
@Override
|
||||
public String get(HttpServletRequest request, String key) {
|
||||
return request.getHeader(key);
|
||||
}
|
||||
};
|
||||
|
||||
private final OpenTelemetrySdk sdk;
|
||||
private final OpenTelemetry otel;
|
||||
|
||||
public Telemetry(DataSource dataSource) {
|
||||
sdk =
|
||||
System.getenv("OTEL_EXPORTER_OTLP_ENDPOINT") == null
|
||||
? null
|
||||
: AutoConfiguredOpenTelemetrySdk.builder()
|
||||
.disableShutdownHook()
|
||||
.build()
|
||||
.getOpenTelemetrySdk();
|
||||
otel = sdk == null ? OpenTelemetry.noop() : sdk;
|
||||
registerProcess();
|
||||
if (dataSource instanceof HikariDataSource pool) {
|
||||
registerPool(pool);
|
||||
}
|
||||
}
|
||||
|
||||
public OpenTelemetry openTelemetry() {
|
||||
return otel;
|
||||
}
|
||||
|
||||
public Span server(HttpServletRequest request) {
|
||||
Context parent =
|
||||
otel.getPropagators()
|
||||
.getTextMapPropagator()
|
||||
.extract(Context.root(), request, HEADERS);
|
||||
return otel.getTracer(SCOPE)
|
||||
.spanBuilder("HTTP request")
|
||||
.setParent(parent)
|
||||
.setSpanKind(SpanKind.SERVER)
|
||||
.startSpan();
|
||||
}
|
||||
|
||||
public Map<String, String> carrier() {
|
||||
Map<String, String> value = new HashMap<>();
|
||||
otel.getPropagators().getTextMapPropagator().inject(Context.current(), value, SETTER);
|
||||
return value;
|
||||
}
|
||||
|
||||
public <T> T dependency(String name, Supplier<T> operation) {
|
||||
Span span =
|
||||
otel.getTracer(SCOPE).spanBuilder(name).setSpanKind(SpanKind.CLIENT).startSpan();
|
||||
try (var scope = span.makeCurrent()) {
|
||||
return operation.get();
|
||||
} catch (RuntimeException error) {
|
||||
span.setStatus(StatusCode.ERROR);
|
||||
span.setAttribute("error.type", error.getClass().getSimpleName());
|
||||
throw error;
|
||||
} finally {
|
||||
span.end();
|
||||
}
|
||||
}
|
||||
|
||||
public void log(String event, boolean error, Attributes attributes) {
|
||||
otel.getLogsBridge()
|
||||
.get(SCOPE)
|
||||
.logRecordBuilder()
|
||||
.setSeverity(error ? Severity.ERROR : Severity.INFO)
|
||||
.setContext(Context.current())
|
||||
.setBody(event)
|
||||
.setAllAttributes(attributes)
|
||||
.emit();
|
||||
}
|
||||
|
||||
private void registerProcess() {
|
||||
var meter = otel.getMeter(SCOPE);
|
||||
if (ManagementFactory.getOperatingSystemMXBean() instanceof OperatingSystemMXBean process) {
|
||||
meter.counterBuilder("lab_process_cpu")
|
||||
.ofDoubles()
|
||||
.setUnit("s")
|
||||
.buildWithCallback(result -> result.record(process.getProcessCpuTime() / 1e9));
|
||||
}
|
||||
meter.gaugeBuilder("lab_process_rss")
|
||||
.ofLongs()
|
||||
.setUnit("By")
|
||||
.buildWithCallback(
|
||||
result -> {
|
||||
try (var lines = Files.lines(Path.of("/proc/self/status"))) {
|
||||
lines.filter(line -> line.startsWith("VmRSS:"))
|
||||
.findFirst()
|
||||
.ifPresent(
|
||||
line ->
|
||||
result.record(
|
||||
Long.parseLong(line.split("\s+")[1])
|
||||
* 1024));
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private void registerPool(HikariDataSource pool) {
|
||||
var meter = otel.getMeter(SCOPE);
|
||||
meter.gaugeBuilder("lab_db_pool_connections")
|
||||
.ofLongs()
|
||||
.buildWithCallback(
|
||||
result -> {
|
||||
var state = pool.getHikariPoolMXBean();
|
||||
if (state != null) {
|
||||
result.record(
|
||||
state.getActiveConnections(),
|
||||
Attributes.of(AttributeKey.stringKey("state"), "used"));
|
||||
result.record(
|
||||
state.getThreadsAwaitingConnection(),
|
||||
Attributes.of(AttributeKey.stringKey("state"), "waiting"));
|
||||
result.record(
|
||||
pool.getMaximumPoolSize(),
|
||||
Attributes.of(AttributeKey.stringKey("state"), "capacity"));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (sdk != null) {
|
||||
sdk.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package ru.mtusi.messenger.util;
|
||||
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.util.Base64;
|
||||
import java.util.UUID;
|
||||
|
||||
public final class CursorCodec {
|
||||
|
||||
private CursorCodec() {}
|
||||
|
||||
public record PageBoundary(Instant createdAt, UUID id) {}
|
||||
|
||||
public record Cursor(UUID scopeId, PageBoundary boundary) {}
|
||||
|
||||
public static String encode(UUID scopeId, PageBoundary boundary) {
|
||||
String raw =
|
||||
(scopeId == null ? "" : scopeId.toString())
|
||||
+ "|"
|
||||
+ boundary.createdAt()
|
||||
+ "|"
|
||||
+ boundary.id();
|
||||
return Base64.getUrlEncoder()
|
||||
.withoutPadding()
|
||||
.encodeToString(raw.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
public static Cursor decode(String cursor) {
|
||||
try {
|
||||
String raw = new String(Base64.getUrlDecoder().decode(cursor), StandardCharsets.UTF_8);
|
||||
String[] p = raw.split("\\|", -1);
|
||||
UUID scopeId = p[0].isEmpty() ? null : UUID.fromString(p[0]);
|
||||
PageBoundary boundary = new PageBoundary(Instant.parse(p[1]), UUID.fromString(p[2]));
|
||||
return new Cursor(scopeId, boundary);
|
||||
} catch (Exception e) {
|
||||
throw new InvalidRequestException("Invalid cursor");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package ru.mtusi.messenger.util;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
@Component
|
||||
public class TokenGenerator {
|
||||
private final SecureRandom rng = new SecureRandom();
|
||||
|
||||
public String generate() {
|
||||
byte[] raw = new byte[32];
|
||||
rng.nextBytes(raw);
|
||||
return Base64.getUrlEncoder().withoutPadding().encodeToString(raw);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package ru.mtusi.messenger.util;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
|
||||
@Component("tokenHasher")
|
||||
public class TokenHasher {
|
||||
|
||||
public byte[] sha256(String token) {
|
||||
try {
|
||||
return MessageDigest.getInstance("SHA-256")
|
||||
.digest(token.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (NoSuchAlgorithmException e) {
|
||||
throw new IllegalStateException("SHA-256 not available", e);
|
||||
}
|
||||
}
|
||||
|
||||
public String hash(String token) {
|
||||
return toHex(sha256(token));
|
||||
}
|
||||
|
||||
public String hash(byte[] bytes) {
|
||||
return toHex(bytes);
|
||||
}
|
||||
|
||||
private String toHex(byte[] bytes) {
|
||||
StringBuilder sb = new StringBuilder(bytes.length * 2);
|
||||
for (byte b : bytes) {
|
||||
sb.append(Character.forDigit((b >> 4) & 0xF, 16));
|
||||
sb.append(Character.forDigit(b & 0xF, 16));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package ru.mtusi.messenger.util.converter;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import tools.jackson.core.JacksonException;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class IdempotencyPayloadConverter {
|
||||
|
||||
private final JsonMapper jsonMapper;
|
||||
|
||||
public String toJson(Object payload) {
|
||||
try {
|
||||
return jsonMapper.writeValueAsString(payload);
|
||||
} catch (JacksonException e) {
|
||||
throw new IllegalStateException("Cannot serialize idempotency payload", e);
|
||||
}
|
||||
}
|
||||
|
||||
public <T> T fromJson(String json, Class<T> type) {
|
||||
try {
|
||||
return jsonMapper.readValue(json, type);
|
||||
} catch (JacksonException e) {
|
||||
throw new IllegalStateException("Corrupt idempotency payload", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package ru.mtusi.messenger.validation;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import ru.mtusi.messenger.config.properties.UploadProperties;
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
import ru.mtusi.messenger.exception.PayloadTooLargeException;
|
||||
import ru.mtusi.messenger.exception.UnsupportedMediaTypeException;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Locale;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import javax.imageio.ImageReader;
|
||||
import javax.imageio.stream.MemoryCacheImageInputStream;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class AttachmentValidator {
|
||||
private final UploadProperties props;
|
||||
|
||||
public String validate(byte[] bytes, String filename) {
|
||||
if (bytes.length > props.maxBytes()) {
|
||||
throw new PayloadTooLargeException("File exceeds max size");
|
||||
}
|
||||
try (var input = new MemoryCacheImageInputStream(new ByteArrayInputStream(bytes))) {
|
||||
var readers = ImageIO.getImageReaders(input);
|
||||
if (!readers.hasNext()) {
|
||||
throw new UnsupportedMediaTypeException("Only PNG/JPEG allowed");
|
||||
}
|
||||
ImageReader reader = readers.next();
|
||||
try {
|
||||
reader.setInput(input, true, true);
|
||||
return inspect(reader);
|
||||
} finally {
|
||||
reader.dispose();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw new UnsupportedMediaTypeException("Corrupted or unsupported image");
|
||||
}
|
||||
}
|
||||
|
||||
private String inspect(ImageReader reader) throws IOException {
|
||||
String mime = contentType(reader.getFormatName());
|
||||
validateDimensions(reader.getWidth(0), reader.getHeight(0));
|
||||
reader.read(0);
|
||||
return mime;
|
||||
}
|
||||
|
||||
private String contentType(String format) {
|
||||
return switch (format.toLowerCase(Locale.ROOT)) {
|
||||
case "png" -> "image/png";
|
||||
case "jpeg", "jpg" -> "image/jpeg";
|
||||
default -> throw new UnsupportedMediaTypeException("Only PNG/JPEG allowed");
|
||||
};
|
||||
}
|
||||
|
||||
private void validateDimensions(int width, int height) {
|
||||
if (width <= 0 || height <= 0) {
|
||||
throw new UnsupportedMediaTypeException("Invalid image dimensions");
|
||||
}
|
||||
if ((long) width * height > props.maxPixels()) {
|
||||
throw new PayloadTooLargeException("Image dimensions exceed limit");
|
||||
}
|
||||
}
|
||||
|
||||
public String sanitizeFilename(String filename) {
|
||||
if (filename == null
|
||||
|| filename.isBlank()
|
||||
|| filename.codePointCount(0, filename.length()) > 255
|
||||
|| filename.contains("/")
|
||||
|| filename.contains("\\")
|
||||
|| filename.codePoints().anyMatch(Character::isISOControl)) {
|
||||
throw new InvalidRequestException("Invalid filename");
|
||||
}
|
||||
return filename;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package ru.mtusi.messenger.validation;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import ru.mtusi.messenger.dto.CreateChatDTO;
|
||||
import ru.mtusi.messenger.exception.InvalidRequestException;
|
||||
import ru.mtusi.messenger.exception.NotFoundException;
|
||||
import ru.mtusi.messenger.model.User;
|
||||
import ru.mtusi.messenger.service.UserService;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class ChatValidator {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
public Set<User> validateCreate(UUID caller, CreateChatDTO createChatDTO) {
|
||||
List<UUID> memberIds = createChatDTO.getMemberIds();
|
||||
String title = createChatDTO.getTitle();
|
||||
|
||||
requireNotBlank(title, "Title must not be blank");
|
||||
requireNonEmpty(memberIds, "member_ids must not be empty");
|
||||
requireNoDuplicates(memberIds, "member_ids contains duplicates");
|
||||
requireContains(memberIds, caller, "Вызывающий должен быть участником");
|
||||
|
||||
return requireAllUsersExist(memberIds);
|
||||
}
|
||||
|
||||
private void requireNotBlank(String value, String message) {
|
||||
if (value == null || value.trim().isEmpty()) {
|
||||
throw new InvalidRequestException(message);
|
||||
}
|
||||
}
|
||||
|
||||
private void requireNonEmpty(List<UUID> ids, String message) {
|
||||
if (ids == null || ids.isEmpty()) {
|
||||
throw new InvalidRequestException(message);
|
||||
}
|
||||
}
|
||||
|
||||
private void requireNoDuplicates(List<UUID> ids, String message) {
|
||||
Set<UUID> unique = new HashSet<>(ids);
|
||||
if (unique.size() != ids.size()) {
|
||||
throw new InvalidRequestException(message);
|
||||
}
|
||||
}
|
||||
|
||||
private void requireContains(List<UUID> ids, UUID value, String message) {
|
||||
if (!ids.contains(value)) {
|
||||
throw new InvalidRequestException(message);
|
||||
}
|
||||
}
|
||||
|
||||
private Set<User> requireAllUsersExist(List<UUID> ids) {
|
||||
try {
|
||||
return userService.requireUsers(ids);
|
||||
} catch (NotFoundException e) {
|
||||
throw new InvalidRequestException(e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user