From a3acf1536e03d7ede01d553c5c6ed061cf65afe8 Mon Sep 17 00:00:00 2001 From: HellsTomato Date: Tue, 27 Oct 2026 13:10:59 +0300 Subject: [PATCH] =?UTF-8?q?=D0=98=D1=81=D0=BF=D1=80=D0=B0=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20=D0=BE=D1=81=D1=82=D0=B0=D0=B2=D1=88=D0=B8=D0=B5?= =?UTF-8?q?=D1=81=D1=8F=20=D0=B7=D0=B0=D0=BC=D0=B5=D1=87=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D1=8F=20lab2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Исправить загрузку чата, валидацию входа, миграцию схемы и режим restart.sh. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- REPORT.md | 4 ++ scripts/restart.sh | 0 .../mtusi/messenger/MessengerApplication.java | 40 +++++++++++++++---- src/main/resources/application.properties | 2 +- .../{schema.sql => db/migration/V1__init.sql} | 13 +++--- 5 files changed, 45 insertions(+), 14 deletions(-) mode change 100644 => 100755 scripts/restart.sh rename src/main/resources/{schema.sql => db/migration/V1__init.sql} (71%) diff --git a/REPORT.md b/REPORT.md index b3317553..6599e5a7 100644 --- a/REPORT.md +++ b/REPORT.md @@ -93,6 +93,10 @@ PostgreSQL является основным источником данных. и внешние ключи. Username уникален. Для истории сообщений создан индекс `(chat_id, created_at, id)`. +Схема создаётся версионируемой миграцией +`src/main/resources/db/migration/V1__init.sql`. Таблица `schema_version` +фиксирует применённую версию, поэтому запуск можно повторять без дублирования. + ### 5. Показать Redis и TTL сессии Сначала выполнить smoke и найти ключ сессии: diff --git a/scripts/restart.sh b/scripts/restart.sh old mode 100644 new mode 100755 diff --git a/src/main/java/ru/mtusi/messenger/MessengerApplication.java b/src/main/java/ru/mtusi/messenger/MessengerApplication.java index 1f0dd8cc..651811df 100644 --- a/src/main/java/ru/mtusi/messenger/MessengerApplication.java +++ b/src/main/java/ru/mtusi/messenger/MessengerApplication.java @@ -6,13 +6,16 @@ import jakarta.servlet.http.*; import org.springframework.boot.*; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer; +import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.Bean; +import org.springframework.core.io.ClassPathResource; import com.fasterxml.jackson.databind.JsonNode; import org.springframework.dao.DuplicateKeyException; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.http.*; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.web.bind.annotation.*; import org.springframework.web.filter.OncePerRequestFilter; @@ -53,6 +56,13 @@ public class MessengerApplication { return builder -> builder.featuresToDisable(MapperFeature.ALLOW_COERCION_OF_SCALARS); } + // Выполняем версионируемую миграцию до создания REST API. + @Bean(name="migration") + Object migration(javax.sql.DataSource dataSource) { + new ResourceDatabasePopulator(new ClassPathResource("db/migration/V1__init.sql")).execute(dataSource); + return new Object(); + } + // @Bean регистрирует фильтр в контейнере Spring. // Фильтр добавляет общий идентификатор каждому HTTP-ответу. @Bean OncePerRequestFilter requestId() { @@ -110,6 +120,7 @@ public class MessengerApplication { // @RestController объединяет @Controller и @ResponseBody. // Методы этого класса принимают HTTP-запросы и возвращают JSON. + @DependsOn("migration") @RestController static class Api { // JdbcTemplate работает с PostgreSQL, RedisTemplate — с Redis-сессиями. @@ -161,12 +172,21 @@ public class MessengerApplication { // Пользователь должен состоять в чате, иначе ресурс для него скрыт. return Boolean.TRUE.equals(db.queryForObject("select exists(select 1 from chat_members where chat_id=? and user_id=?)",Boolean.class,chat,user)); } + // Загружает один чат и его участников напрямую по идентификатору. + Chat chatById(UUID id) { + return db.query("select id,title,created_at from chats where id=?",rs -> rs.next() + ? new Chat(rs.getObject(1,UUID.class),rs.getString(2), + db.query("select user_id from chat_members where chat_id=?",(z,k)->z.getObject(1,UUID.class),id), + rs.getTimestamp(3).toInstant()) : null,id); + } // Считает символы как Unicode code points, а не как UTF-16 char. int codePointLength(String value) { return value.codePointCount(0,value.length()); } // Возвращает значение только если JSON-поле действительно является строкой. String string(JsonNode value) { return value!=null && value.isTextual()?value.textValue():null; } + // PostgreSQL не хранит нулевой байт, поэтому заменяем его безопасным символом. + String databaseText(String value) { return value==null?null:value.replace('\0','\uFFFD'); } // Проверяет обязательную непустую строку и её максимальную длину. boolean text(String value, int max) { return value!=null && !value.isBlank() && codePointLength(value)<=max; } // Предварительный SHA-256 сохраняет весь пароль перед ограниченным BCrypt. @@ -189,7 +209,8 @@ public class MessengerApplication { String displayName=in==null?null:string(in.display_name()); String password=in==null?null:string(in.password()); // До запроса в базу проверяем формат обязательных полей. - if(username==null || !username.matches("[a-z0-9_]{3,32}") || !text(displayName,100) || password==null || codePointLength(password)<12 || codePointLength(password)>128) bad(); + if(username==null || !username.matches("[a-z0-9_]{3,32}") || !text(displayName,100) || password==null || password.isBlank() || codePointLength(password)<12 || codePointLength(password)>128) bad(); + displayName=databaseText(displayName); // Создаём UUID пользователя и фиксируем время регистрации. UUID id=UUID.randomUUID(); Instant now=Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS); // Значения передаются параметрами, а не склеиваются со строкой SQL. @@ -242,6 +263,7 @@ public class MessengerApplication { // ID и время создаются сервером. UUID id=UUID.randomUUID(); Instant now=Instant.now(); // Записываем чат и участников в одной транзакции. + title=databaseText(title); db.update("insert into chats values(?,?,?)",id,title,java.sql.Timestamp.from(now)); for(UUID m:in.member_ids()) db.update("insert into chat_members values(?,?)",id,m); // Возвращаем созданную модель чата. return ResponseEntity.status(201).body(new Chat(id,title,in.member_ids(),now)); @@ -277,23 +299,25 @@ public class MessengerApplication { Chat chat(@PathVariable UUID id,HttpServletRequest r) { // Сначала проверяем токен и членство в чате. UUID u=auth(r); if(!member(id,u)) throw notFound(); - // Затем находим сам чат в списке доступных объектов. - return chats(r).items().stream().filter(x->x.id().equals(id)).findFirst().orElseThrow(this::notFound); + // Загружаем чат напрямую, поэтому поздние записи не зависят от первой страницы списка. + Chat result=chatById(id); + if(result==null) throw notFound(); + return result; } // POST-запрос добавляет сообщение в выбранный чат. // @PathVariable получает id чата, а @RequestBody — текст из JSON. @PostMapping("/api/v1/chats/{id}/messages") ResponseEntity message(@PathVariable UUID id,@RequestBody MessageIn in,HttpServletRequest r) { // Автор сообщения берётся из сессии, а не из тела запроса. - String messageText=in==null?null:string(in.text()); + String messageText=databaseText(in==null?null:string(in.text())); UUID u=auth(r); if(!member(id,u)) throw notFound(); if(!text(messageText,4000)) bad(); // Сервер создаёт ID и время сообщения. UUID mid=UUID.randomUUID(); Instant now=Instant.now().truncatedTo(java.time.temporal.ChronoUnit.MICROS); db.update("insert into messages values(?,?,?,?,?)",mid,id,u,messageText,java.sql.Timestamp.from(now)); return ResponseEntity.status(201).body(new Message(mid,id,u,messageText,now)); } // GET-запрос возвращает историю сообщений с cursor-пагинацией. // @RequestParam получает limit и cursor из параметров URL. - @GetMapping("/api/v1/chats/{id}/messages") Page messages(@PathVariable UUID id,@RequestParam(defaultValue="50") int limit,@RequestParam(required=false) String cursor,HttpServletRequest r) { + @GetMapping("/api/v1/chats/{id}/messages") Page messages(@PathVariable UUID id,@RequestParam(required=false) String limit,@RequestParam(required=false) String cursor,HttpServletRequest r) { // Историю может читать только участник чата. - UUID u=auth(r); if(!member(id,u)) throw notFound(); if(limit<1||limit>100) bad(); + UUID u=auth(r); if(!member(id,u)) throw notFound(); int pageLimit=parseLimit(limit); // Начинаем параметризованный запрос истории. String sql="select id,chat_id,sender_id,text,created_at from messages where chat_id=? "; // Список параметров передаётся в JdbcTemplate отдельно от SQL. @@ -309,11 +333,11 @@ public class MessengerApplication { } catch(Exception e) { bad(); } } // Сортируем историю и берём одну запись сверх лимита для следующего cursor. - sql+="order by created_at,id limit ?"; args.add(limit+1); + sql+="order by created_at,id limit ?"; args.add(pageLimit+1); // Выполняем запрос и превращаем строки базы в объекты Message. List x=db.query(sql,(rs,n)->new Message(rs.getObject(1,UUID.class),rs.getObject(2,UUID.class),rs.getObject(3,UUID.class),rs.getString(4),rs.getTimestamp(5).toInstant()),args.toArray()); // Если запись сверх лимита есть, кодируем её позицию как следующий cursor. - String next=x.size()>limit?Base64.getUrlEncoder().withoutPadding().encodeToString((id+"|"+x.get(limit-1).created_at()+"|"+x.get(limit-1).id()).getBytes(StandardCharsets.UTF_8)):null; return new Page<>(x.subList(0,Math.min(limit,x.size())),next); + String next=x.size()>pageLimit?Base64.getUrlEncoder().withoutPadding().encodeToString((id+"|"+x.get(pageLimit-1).created_at()+"|"+x.get(pageLimit-1).id()).getBytes(StandardCharsets.UTF_8)):null; return new Page<>(x.subList(0,Math.min(pageLimit,x.size())),next); } // Преобразует limit списка чатов в число и проверяет диапазон. int parseLimit(String value) { try { int limit=value==null?50:Integer.parseInt(value); if(limit<1||limit>100) bad(); return limit; } catch(NumberFormatException e) { bad(); return 0; } } diff --git a/src/main/resources/application.properties b/src/main/resources/application.properties index 22b58c96..d21bda5a 100644 --- a/src/main/resources/application.properties +++ b/src/main/resources/application.properties @@ -12,5 +12,5 @@ spring.datasource.hikari.connection-init-sql=SET statement_timeout = '3000'; SET spring.data.redis.host=${SPRING_DATA_REDIS_HOST:localhost} spring.data.redis.port=${SPRING_DATA_REDIS_PORT:6379} spring.data.redis.timeout=2s -spring.sql.init.mode=always +spring.sql.init.mode=never spring.jackson.mapper.allow-coercion-of-scalars=false diff --git a/src/main/resources/schema.sql b/src/main/resources/db/migration/V1__init.sql similarity index 71% rename from src/main/resources/schema.sql rename to src/main/resources/db/migration/V1__init.sql index 6fd5d86f..196d5f5e 100644 --- a/src/main/resources/schema.sql +++ b/src/main/resources/db/migration/V1__init.sql @@ -1,24 +1,27 @@ --- Пользователи приложения и хеши их паролей. +-- Version 1 creates the complete messenger schema. +CREATE TABLE IF NOT EXISTS schema_version ( + version VARCHAR(20) PRIMARY KEY, + applied_at TIMESTAMPTZ NOT NULL +); CREATE TABLE IF NOT EXISTS users ( id UUID PRIMARY KEY, username VARCHAR(32) UNIQUE NOT NULL, display_name VARCHAR(100) NOT NULL, password_hash VARCHAR(100) NOT NULL, created_at TIMESTAMPTZ NOT NULL ); --- Чаты, созданные пользователями. CREATE TABLE IF NOT EXISTS chats ( id UUID PRIMARY KEY, title VARCHAR(100) NOT NULL, created_at TIMESTAMPTZ NOT NULL ); --- Связь пользователей с чатами. CREATE TABLE IF NOT EXISTS chat_members ( chat_id UUID REFERENCES chats(id) ON DELETE CASCADE, user_id UUID REFERENCES users(id) ON DELETE CASCADE, PRIMARY KEY (chat_id, user_id) ); --- Сообщения внутри чатов. CREATE TABLE IF NOT EXISTS messages ( id UUID PRIMARY KEY, chat_id UUID REFERENCES chats(id) ON DELETE CASCADE, sender_id UUID REFERENCES users(id), text VARCHAR(4000) NOT NULL, created_at TIMESTAMPTZ NOT NULL ); --- Индекс ускоряет получение истории сообщений. CREATE INDEX IF NOT EXISTS messages_history ON messages(chat_id, created_at, id); +INSERT INTO schema_version(version, applied_at) +VALUES ('V1__init', now()) +ON CONFLICT (version) DO NOTHING;