package ru.mtusi.lab4; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.sql.*; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.UUID; final class DatabaseStore implements AutoCloseable { private final String url; private final String user; private final String password; DatabaseStore() { this.url = setting("DATABASE_URL", "jdbc:postgresql://localhost:5432/messenger"); this.user = setting("DATABASE_USER", "messenger"); this.password = setting("DATABASE_PASSWORD", "messenger"); try { Class.forName("org.postgresql.Driver"); migrate(); } catch (Exception e) { throw new IllegalStateException("database initialization failed", e); } } private static String setting(String name, String fallback) { String value = System.getenv(name); return value == null || value.isBlank() ? fallback : value.trim(); } private Connection connection() throws SQLException { return DriverManager.getConnection(url, user, password); } private void migrate() throws SQLException, IOException { try (Connection c = connection()) { c.setAutoCommit(false); try (Statement s = c.createStatement()) { s.execute("SELECT pg_advisory_xact_lock(3103)"); s.execute("CREATE TABLE IF NOT EXISTS schema_version (version integer primary key, applied_at timestamptz not null default now())"); try (ResultSet rs = s.executeQuery("SELECT count(*) FROM schema_version WHERE version=1")) { rs.next(); if (rs.getInt(1) == 0) { String sql; try (InputStream in = DatabaseStore.class.getResourceAsStream("/db/migration/V1__initial.sql")) { if (in == null) throw new IOException("migration resource missing"); sql = new String(in.readAllBytes(), StandardCharsets.UTF_8); } for (String statement : sql.split(";")) { if (!statement.isBlank()) s.execute(statement); } s.execute("INSERT INTO schema_version(version) VALUES (1)"); } } } c.commit(); } } User createUser(String username, String displayName, String passwordHash) { UUID id = UUID.randomUUID(); try (Connection c = connection(); PreparedStatement p = c.prepareStatement( "INSERT INTO users(id,username,display_name,password_hash) VALUES (?,?,?,?)")) { p.setObject(1, id); p.setString(2, username); p.setString(3, displayName); p.setString(4, passwordHash); p.executeUpdate(); return findUser(id).orElseThrow(ApiException::unavailable); } catch (SQLException e) { if ("23505".equals(e.getSQLState())) throw ApiException.conflict(); throw unavailable(e); } } Optional credential(String username) { try (Connection c = connection(); PreparedStatement p = c.prepareStatement("SELECT id,username,display_name,created_at,password_hash FROM users WHERE username=?")) { p.setString(1, username); try (ResultSet r = p.executeQuery()) { return r.next() ? Optional.of(new Credential(user(r), r.getString("password_hash"))) : Optional.empty(); } } catch (SQLException e) { throw unavailable(e); } } Optional findUser(UUID id) { try (Connection c = connection(); PreparedStatement p = c.prepareStatement( "SELECT id,username,display_name,created_at FROM users WHERE id=?")) { p.setObject(1, id); try (ResultSet r = p.executeQuery()) { return r.next() ? Optional.of(user(r)) : Optional.empty(); } } catch (SQLException e) { throw unavailable(e); } } Session createSession(UUID userId, String token, Instant expiresAt) { try (Connection c = connection(); PreparedStatement p = c.prepareStatement( "INSERT INTO sessions(token,user_id,expires_at) VALUES (?,?,?)")) { p.setString(1, token); p.setObject(2, userId); p.setTimestamp(3, Timestamp.from(expiresAt)); p.executeUpdate(); return new Session(token, expiresAt, findUser(userId).orElseThrow(ApiException::unauthorized)); } catch (SQLException e) { throw unavailable(e); } } Optional session(String token) { try (Connection c = connection(); PreparedStatement p = c.prepareStatement( "SELECT s.token,s.expires_at,u.id,u.username,u.display_name,u.created_at " + "FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token=? AND s.expires_at>now()")) { p.setString(1, token); try (ResultSet r = p.executeQuery()) { if (!r.next()) return Optional.empty(); return Optional.of(new Session(r.getString("token"), r.getTimestamp("expires_at").toInstant(), user(r))); } } catch (SQLException e) { throw unavailable(e); } } void revoke(String token) { try (Connection c = connection(); PreparedStatement p = c.prepareStatement("DELETE FROM sessions WHERE token=?")) { p.setString(1, token); p.executeUpdate(); } catch (SQLException e) { throw unavailable(e); } } Chat createChat(UUID callerId, String title, List members) { UUID id = UUID.randomUUID(); try (Connection c = connection()) { c.setAutoCommit(false); try { for (UUID member : members) { try (PreparedStatement p = c.prepareStatement("SELECT 1 FROM users WHERE id=?")) { p.setObject(1, member); try (ResultSet r = p.executeQuery()) { if (!r.next()) throw ApiException.invalid("Указан неизвестный участник"); } } } Instant now = Instant.now(); try (PreparedStatement p = c.prepareStatement("INSERT INTO chats(id,title,created_at) VALUES (?,?,?)")) { p.setObject(1, id); p.setString(2, title); p.setTimestamp(3, Timestamp.from(now)); p.executeUpdate(); } try (PreparedStatement p = c.prepareStatement("INSERT INTO chat_members(chat_id,user_id) VALUES (?,?)")) { for (UUID member : members) { p.setObject(1, id); p.setObject(2, member); p.addBatch(); } p.executeBatch(); } c.commit(); return new Chat(id, title, List.copyOf(members), now); } catch (RuntimeException | SQLException e) { c.rollback(); if (e instanceof ApiException a) throw a; if (e instanceof SQLException sql) throw unavailable(sql); throw ApiException.unavailable(); } } catch (SQLException e) { throw unavailable(e); } } List chatsOf(UUID userId) { List result = new ArrayList<>(); String sql = "SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=? ORDER BY c.created_at,c.id"; try (Connection c = connection(); PreparedStatement p = c.prepareStatement(sql)) { p.setObject(1, userId); try (ResultSet r = p.executeQuery()) { while (r.next()) result.add(chat(c, r)); } return result; } catch (SQLException e) { throw unavailable(e); } } Optional visibleChat(UUID userId, UUID chatId) { try (Connection c = connection(); PreparedStatement p = c.prepareStatement( "SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE c.id=? AND m.user_id=?")) { p.setObject(1, chatId); p.setObject(2, userId); try (ResultSet r = p.executeQuery()) { return r.next() ? Optional.of(chat(c, r)) : Optional.empty(); } } catch (SQLException e) { throw unavailable(e); } } Message addMessage(UUID senderId, UUID chatId, String text) { if (visibleChat(senderId, chatId).isEmpty()) throw ApiException.notFound(); UUID id = UUID.randomUUID(); Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); try (Connection c = connection(); PreparedStatement p = c.prepareStatement( "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES (?,?,?,?,?)")) { p.setObject(1,id); p.setObject(2,chatId); p.setObject(3,senderId); p.setString(4,text); p.setTimestamp(5, Timestamp.from(now)); p.executeUpdate(); return new Message(id, chatId, senderId, text, now); } catch (SQLException e) { throw unavailable(e); } } Optional idempotentMessage(UUID senderId, UUID chatId, String key, String bodyHash) { try (Connection c = connection(); PreparedStatement p = c.prepareStatement( "SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,i.body_hash " + "FROM idempotency_keys i JOIN messages m ON m.id=i.message_id " + "WHERE i.user_id=? AND i.chat_id=? AND i.key=?")) { p.setObject(1, senderId); p.setObject(2, chatId); p.setString(3, key); try (ResultSet r = p.executeQuery()) { if (!r.next()) return Optional.empty(); if (!r.getString("body_hash").equals(bodyHash)) throw ApiException.conflict(); return Optional.of(new Message((UUID) r.getObject("id"), (UUID) r.getObject("chat_id"), (UUID) r.getObject("sender_id"), r.getString("text"), r.getTimestamp("created_at").toInstant())); } } catch (SQLException e) { throw unavailable(e); } } Message addIdempotentMessage(UUID senderId, UUID chatId, String key, String bodyHash, String text) { if (visibleChat(senderId, chatId).isEmpty()) throw ApiException.notFound(); try (Connection c = connection()) { c.setAutoCommit(false); try { UUID id = UUID.randomUUID(); Instant now = Instant.now().truncatedTo(ChronoUnit.MICROS); try (PreparedStatement p = c.prepareStatement( "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES (?,?,?,?,?)")) { p.setObject(1,id); p.setObject(2,chatId); p.setObject(3,senderId); p.setString(4,text); p.setTimestamp(5,Timestamp.from(now)); p.executeUpdate(); } try (PreparedStatement p = c.prepareStatement( "INSERT INTO idempotency_keys(user_id,chat_id,key,body_hash,message_id) VALUES (?,?,?,?,?)")) { p.setObject(1,senderId); p.setObject(2,chatId); p.setString(3,key); p.setString(4,bodyHash); p.setObject(5,id); p.executeUpdate(); } c.commit(); return new Message(id, chatId, senderId, text, now); } catch (SQLException e) { c.rollback(); if ("23505".equals(e.getSQLState())) { return idempotentMessage(senderId, chatId, key, bodyHash).orElseThrow(ApiException::unavailable); } throw unavailable(e); } } catch (SQLException e) { throw unavailable(e); } } Optional attachment(UUID userId, UUID id) { try (Connection c = connection(); PreparedStatement p = c.prepareStatement( "SELECT a.* FROM attachments a JOIN chat_members m ON m.chat_id=a.chat_id WHERE a.id=? AND m.user_id=?")) { p.setObject(1,id); p.setObject(2,userId); try (ResultSet r=p.executeQuery()) { return r.next() ? Optional.of(attachment(r)) : Optional.empty(); } } catch (SQLException e) { throw unavailable(e); } } Attachment createAttachment(UUID ownerId, UUID chatId, String filename, String type, long size, String sha, String objectKey) { if (visibleChat(ownerId, chatId).isEmpty()) throw ApiException.notFound(); UUID id=UUID.randomUUID(); Instant now=Instant.now(); try(Connection c=connection(); PreparedStatement p=c.prepareStatement( "INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?)")){ p.setObject(1,id);p.setObject(2,chatId);p.setObject(3,ownerId);p.setString(4,filename);p.setString(5,type);p.setLong(6,size);p.setString(7,sha);p.setString(8,objectKey);p.setTimestamp(9,Timestamp.from(now));p.setTimestamp(10,Timestamp.from(now));p.executeUpdate(); return new Attachment(id,chatId,ownerId,filename,type,size,sha,objectKey,now,now); } catch(SQLException e){throw unavailable(e);} } void attachToMessage(UUID userId, UUID messageId, UUID chatId, List ids) { if (visibleChat(userId,chatId).isEmpty()) throw ApiException.notFound(); try(Connection c=connection(); PreparedStatement p=c.prepareStatement("INSERT INTO message_attachments(message_id,attachment_id) VALUES (?,?)")){ for(UUID id:ids){try(PreparedStatement q=c.prepareStatement("SELECT id FROM attachments WHERE id=? AND chat_id=?")){q.setObject(1,id);q.setObject(2,chatId);try(ResultSet r=q.executeQuery()){if(!r.next())throw ApiException.notFound();}}p.setObject(1,messageId);p.setObject(2,id);p.addBatch();}p.executeBatch(); } catch(ApiException e){throw e;}catch(SQLException e){throw unavailable(e);} } List attachmentIds(UUID messageId) { List ids=new ArrayList<>(); try(Connection c=connection();PreparedStatement p=c.prepareStatement("SELECT attachment_id FROM message_attachments WHERE message_id=? ORDER BY attachment_id")){p.setObject(1,messageId);try(ResultSet r=p.executeQuery()){while(r.next())ids.add((UUID)r.getObject(1));}return ids;}catch(SQLException e){throw unavailable(e);} } List messagesOf(UUID userId, UUID chatId) { if (visibleChat(userId, chatId).isEmpty()) throw ApiException.notFound(); List result = new ArrayList<>(); try (Connection c = connection(); PreparedStatement p = c.prepareStatement( "SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=? ORDER BY created_at,id")) { p.setObject(1, chatId); try (ResultSet r = p.executeQuery()) { while (r.next()) result.add(new Message((UUID)r.getObject("id"), (UUID)r.getObject("chat_id"), (UUID)r.getObject("sender_id"), r.getString("text"), r.getTimestamp("created_at").toInstant())); } return result; } catch (SQLException e) { throw unavailable(e); } } private static User user(ResultSet r) throws SQLException { return new User((UUID) r.getObject("id"), r.getString("username"), r.getString("display_name"), r.getTimestamp("created_at").toInstant()); } private static Chat chat(Connection c, ResultSet r) throws SQLException { List ids = new ArrayList<>(); try (PreparedStatement p = c.prepareStatement("SELECT user_id FROM chat_members WHERE chat_id=? ORDER BY user_id")) { p.setObject(1, r.getObject("id")); try (ResultSet m = p.executeQuery()) { while (m.next()) ids.add((UUID)m.getObject(1)); } } return new Chat((UUID)r.getObject("id"), r.getString("title"), ids, r.getTimestamp("created_at").toInstant()); } private static Attachment attachment(ResultSet r) throws SQLException { return new Attachment((UUID)r.getObject("id"),(UUID)r.getObject("chat_id"),(UUID)r.getObject("owner_id"), r.getString("filename"),r.getString("content_type"),r.getLong("size_bytes"),r.getString("sha256"), r.getString("object_key"),r.getTimestamp("created_at").toInstant(),r.getTimestamp("updated_at").toInstant()); } private static ApiException unavailable(SQLException e) { return ApiException.unavailable(); } @Override public void close() { } record Credential(User user, String passwordHash) {} }