package ru.mtusi.lab2; 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("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); } } 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 ApiException unavailable(SQLException e) { return ApiException.unavailable(); } @Override public void close() { } record Credential(User user, String passwordHash) {} }